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)
添加回答
舉報