【发布时间】:2023-03-11 12:30:01
【问题描述】:
我在 python 中使用threading 动态生成多个线程。这就是我产生线程的方式:
def func(max_val):
for val in range(0,max_val):
thread1 = threading.Thread(target=func9, args=(val,))
thread1.start()
print 'Ended all threads' #this should get printed once all the threads have ended
# bunch of other code after this
.
.
.
if __name__ == '__main__':
ret = func()
我想要的是,一旦所有线程都被生成,那么进程应该等到所有线程都结束,然后继续执行代码中的下一行。我知道我们使用thread1.join() 来等待一个线程,但是如果我将它放在for 循环中,那么它将等待第一个线程结束,然后再生成下一个线程。我不希望它在开始下一个线程之前等待一个线程结束。它应该同时产生所有线程,然后等待所有线程都结束,然后再执行代码中的下一行(就像上面的func() 中的print 应该在所有线程结束后执行)。
我该怎么做?
【问题讨论】:
标签: python multithreading python-multithreading