1 回答
TA贡献1853条经验 获得超6个赞
您可以使用threading.Thread:
from threading import Thread
from time import sleep
from random import randint
def dosomething(var):
sleep(randint(1,5))
print(var)
array = ["a", "b", "c", "d", "e"]
threads = []
for arrayval in array:
threads.append(Thread(target=dosomething, args=(arrayval,)))
threads[-1].start()
for thread in threads:
thread.join()
这会在 5 秒内以随机顺序输出:
e
b
c
a
d
如果要限制线程数,可以multiprocessing.pool.ThreadPool改用。以下示例将工作线程的数量限制为 2,因此可能需要长达 15 秒的时间才能完成(如果所有工作人员恰好需要 5 秒):
from multiprocessing.pool import ThreadPool
from time import sleep
from random import randint
def dosomething(var):
sleep(randint(1,5))
print(var)
array = ["a", "b", "c", "d", "e"]
with ThreadPool(processes=2) as pool:
pool.map(dosomething, array)
添加回答
举报