同时运行相同的 for 循环的不同迭代



还有一个类似的问题,但答案不清楚

尝试通过在同一时间运行每次迭代来加快for循环

for i in something:
print(i) # I would want this code to be executed all at the same time

仍然需要一个for循环,但我假设每个循环中的代码都很长,需要时间,所以下面是如何为每个循环启动一个线程,然后等待所有线程完成后再继续

import threading
def myfunc(*args):
#do something
return
threads=[]
for n,i in enumerate(something):
threads.append(threading.Thread(target = myfunc, args = (i,))) #args needs to be a tuple, even with only 1 element
threads[n].start()
for thread in threads:
thread.join()

最新更新