让主线程等待所有线程完成
我有一个线程的列表,所有线程都是通过 threading.start()
启动的,现在我需要让主线程等到列表里的所有线程都完成。
这可以通过以下方式实现:
[x.join() for x in threads]
不过,每次执行 x.join()
时,其他所有线程也会被阻塞。我想要的是所有线程可以同时运行。主程序应该在所有线程都执行完毕后再继续,而列表中的任何线程在运行时都不应该被阻塞。
根据我的理解,使用 join 方法是无法实现我想要的效果,难道我理解错了吗?
2 个回答
2
这里有一个例子:
from threading import Thread, Lock
from time import sleep
from random import random
def target(i, lock):
with lock:
print("Starting thread {}".format(i))
# Do something
sleep(random()*5)
with lock:
print("Stopping thread {}".format(i))
# Create the threads
lock = Lock()
threads = [Thread(target=target, args=(i, lock)) for i in range(5)]
# Start the threads
for x in threads:
x.start()
# Stop the threads
for x in threads:
x.join()
print("Done!")
这是一个可能的输出结果:
>>>
Starting thread 0
Starting thread 1
Starting thread 2
Starting thread 3
Starting thread 4
Stopping thread 1
Stopping thread 4
Stopping thread 0
Stopping thread 2
Stopping thread 3
Done!
你可以看到,它的运行效果正是你所需要的。
7
不,x.join()
只是会阻塞主线程。其他线程会继续并行执行。
for thread in threads:
thread.join()
这种写法更符合习惯,因为你实际上并没有在构建一个列表。
你还应该知道,在Python中,多线程的表现可能和你预期的不一样,除非你在做一些与输入输出相关的工作(比如频繁访问远程服务),否则你很可能不会获得任何性能提升。