Python 如何等待所有线程完成其工作?
我有以下脚本(不参考内容): 我想并发执行(比如4个线程)func1(),在我的例子中,它包括一个可能需要时间执行的函数调用。然后,只有在最后一个线程完成其工作后,我才想执行验证\u result() 目前,我得到的结果是所有线程都完成了它们的工作,但是在所有线程完成它们的工作之前执行verify_result() 我甚至尝试在for循环下使用以下代码(当然,我导入了线程),但这并没有起作用(不要参考参数)Python 如何等待所有线程完成其工作?,python,multithreading,python-3.x,Python,Multithreading,Python 3.x,我有以下脚本(不参考内容): 我想并发执行(比如4个线程)func1(),在我的例子中,它包括一个可能需要时间执行的函数调用。然后,只有在最后一个线程完成其工作后,我才想执行验证\u result() 目前,我得到的结果是所有线程都完成了它们的工作,但是在所有线程完成它们的工作之前执行verify_result() 我甚至尝试在for循环下使用以下代码(当然,我导入了线程),但这并没有起作用(不要参考参数) 假设您有一个线程列表。 将(每个_线程)循环到它们上- for each_thread
假设您有一个线程列表。 将(每个_线程)循环到它们上-
for each_thread in thread_pool:
each_thread.start()
在循环中开始在每个线程中执行run函数
同样,在启动所有线程并具有
for each_thread in thread_pool:
each_thread.join()
join所做的是等待线程i完成执行,然后再让i+1个线程完成执行
线程将并发运行,join()
将同步每个线程返回结果的方式
具体来说,您可以使用
join()
循环和运行verify_result()
函数。上一个threading
示例已经结束,但您必须收集列表中的线程,一次启动它们,然后等待它们一次完成。下面是一个简化的示例:
import threading
import time
# Lock to serialize console output
output = threading.Lock()
def threadfunc(a,b):
for i in range(a,b):
time.sleep(.01) # sleep to make the "work" take longer
with output:
print(i)
# Collect the threads
threads = []
for i in range(10,100,10):
# Create 9 threads counting 10-19, 20-29, ... 90-99.
thread = threading.Thread(target=threadfunc,args=(i,i+10))
threads.append(thread)
# Start them all
for thread in threads:
thread.start()
# Wait for all to complete
for thread in threads:
thread.join()
我不熟悉Python,尤其是线程。你能再解释一下线程池是什么意思吗?“我如何准备线程列表?”MosheS。所谓线程池,我指的是线程的文字集合。假设您有一个作业需要执行5次,最好是并发执行,您恰好为此创建了(而不是开始执行)2个线程,现在每个线程将占用一个作业,3个作业将等待一个线程空闲时再拾取它们,因此检查线程池是否有线程空闲,否则等待,直到有线程空闲时再拾取。我所说的线程列表是指线程对象的列表。你迭代它们并开始工作,这就是我认为你想要做的。在我的回答中,线程池指的是这样一个列表,而不是线程池。
for each_thread in thread_pool:
each_thread.join()
import threading
import time
# Lock to serialize console output
output = threading.Lock()
def threadfunc(a,b):
for i in range(a,b):
time.sleep(.01) # sleep to make the "work" take longer
with output:
print(i)
# Collect the threads
threads = []
for i in range(10,100,10):
# Create 9 threads counting 10-19, 20-29, ... 90-99.
thread = threading.Thread(target=threadfunc,args=(i,i+10))
threads.append(thread)
# Start them all
for thread in threads:
thread.start()
# Wait for all to complete
for thread in threads:
thread.join()