欢迎访问宙启技术站
智能推送

Python中的wait()函数:如何等待多个线程的完成

发布时间:2024-01-02 15:34:36

在 Python 中,可以使用 threading 模块来创建和管理线程。wait() 函数是 threading 模块中 Condition 类的一个方法,用于等待多个线程的完成。

wait() 方法需要在一个 Condition 对象上调用。Condition 对象定义了一个条件变量,可以用于在多个线程之间协调和同步操作。当调用 wait() 方法时,当前线程会释放锁,并进入阻塞状态,直到其他线程调用 notify() 或 notify_all() 方法唤醒它,或者超时时间到达。

以下是 wait() 方法的语法:

wait([timeout])

其中,timeout 是一个可选的参数,表示等待的最大时间(以秒为单位)。如果 timeout 是 None,那么 wait() 方法将一直等待,直到被唤醒。如果 timeout 不为 None,则表示最长等待时间,超过该时间仍未被唤醒,线程将自动被唤醒并继续执行。

下面是一个使用 wait() 方法等待多个线程的示例:

import threading
import time

def worker(condition, worker_id):
    with condition:
        print(f"Worker {worker_id} is ready.")
        condition.wait()
        print(f"Worker {worker_id} is working.")
        time.sleep(1)
        print(f"Worker {worker_id} is done.")

def main():
    condition = threading.Condition()
    workers = []
    
    for i in range(5):
        worker_thread = threading.Thread(target=worker, args=(condition, i))
        worker_thread.start()
        workers.append(worker_thread)
    
    time.sleep(2)
    
    with condition:
        print("Main thread is waking up all workers.")
        condition.notify_all()
    
    for worker_thread in workers:
        worker_thread.join()

if __name__ == "__main__":
    main()

在这个例子中,我们创建了 5 个 worker 线程,每个线程都会首先调用 wait() 方法进入等待状态。主线程在休眠 2 秒后,调用 notify_all() 方法唤醒所有的 worker 线程。然后主线程会等待每个 worker 线程都完成后再退出。

运行这段代码后,你会看到类似以下的输出:

Worker 1 is ready.
Worker 2 is ready.
Worker 3 is ready.
Worker 0 is ready.
Worker 4 is ready.
Main thread is waking up all workers.
Worker 2 is working.
Worker 4 is working.
Worker 1 is working.
Worker 0 is working.
Worker 3 is working.
Worker 1 is done.
Worker 2 is done.
Worker 3 is done.
Worker 0 is done.
Worker 4 is done.

从输出可以看出,所有的 worker 线程在被唤醒后,开始执行工作,并按照不确定的顺序完成任务。