我正在更新一些看起来像这样的现有代码:
for i in list
thread.start_new_thread(main, (i[0],i[1],i[2],2))
这会导致为列表中的每个项目创建线程,但在创建所有线程之前不会执行。我想要么以小组形式执行线程,要么让它们在创建后直接执行。
(这里有很多 python 线程讨论,很抱歉,如果我错过了已经问过的此类问题......
您可能会
发现concurrent.futures
模块很有用。它也适用于名为 futures
的 Python 2。例如,要同时调用MY_LIST
上每个项目main
函数,但最多 5 个线程,您可以编写:
from concurrent.futures import ThreadPoolExecutor
with ThreadPoolExecutor(max_workers=5) as executor:
for result in executor.map(main, MY_LIST):
# Do something with result
print(result)