python 多线程任务判断子线程所绑定的函数是否全部执行完毕

import threading
import time

def worker(event, thread_name):
    print(f"{thread_name} 正在执行任务...")
    time.sleep(20)
    print(f"{thread_name} 任务执行完成")
    event.set()  # 设置事件为已触发状态

def WatchJoin(threads,event):
    # 等待所有线程完成任务
    for thread in threads:
        thread.join()
    print("WatchJoin Finish!")
    event.wait()
    return True

# 创建一个事件对象
event = threading.Event()
# 创建多个线程,并启动它们
threads = []
for i in range(5):
    thread = threading.Thread(target=worker, args=(event, f"线程{i+1}"))
    thread.start()
    threads.append(thread)

thread = threading.Thread(target=WatchJoin, args=(threads,event))
thread.start()

for i in range(10):
    time.sleep(1)
    print(i)

#  等待事件被设置为已触发状态
# print("所有线程任务已完成")

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python 多线程编程中,线程绑定 GPU 失败的问题可以通过以下几种方式解决: 1. 在每个线程中都调用 `torch.cuda.set_device()` 显式地设置要使用的 GPU 设备。这可以确保在每个线程中使用的 CUDA 上下文与主线程中的一致。例如: ```python import torch import threading def worker(): torch.cuda.set_device(0) # 设置要使用的 GPU 设备 # 在线程中进行 GPU 相关的操作 # 创建线程并启动 thread = threading.Thread(target=worker) thread.start() ``` 2. 将需要在线程中进行的 GPU 相关操作放在一个函数中,然后通过 `torch.cuda.stream()` 创建一个新的 CUDA 流,并将操作放入该流中执行。这样可以避免多个线程之间的 CUDA 上下文冲突。例如: ```python import torch import threading def worker(): # 创建一个新的 CUDA 流 stream = torch.cuda.stream() with torch.cuda.stream(stream): # 在线程中进行 GPU 相关的操作 # 创建线程并启动 thread = threading.Thread(target=worker) thread.start() ``` 3. 使用 `torch.cuda.device()` 上下文管理器手动管理 CUDA 上下文。这样可以确保在线程结束时正确释放 CUDA 资源。例如: ```python import torch import threading def worker(): with torch.cuda.device(0): # 设置要使用的 GPU 设备 # 在线程中进行 GPU 相关的操作 # 创建线程并启动 thread = threading.Thread(target=worker) thread.start() ``` 需要注意的是,多线程环境下使用 GPU 时,要确保正确地管理 CUDA 上下文,避免出现资源泄漏或冲突的问题。并且要根据具体情况选择适合的解决方案。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值