簡體   English   中英

如何用“for”循環多線程?

[英]How to multi-thread with “for” loop?

之前可能已經問過幾次類似的問題,但是它們似乎都沒有我的案例/場景或它不起作用。

我試圖多線程一個for循環,如一個例子中所示。 這個for循環將在循環數組時執行一個函數。 我想多線程。

例:

array = ["a", "b", "c", "d", "e"]
def dosomething(var):
    #dosomething this is just an example as my actual code is not relevant to this question

for arrayval in array:
    dosomething(arrayval)

這應該循環遍歷數組並使用變量abc等執行函數dosomething

關於我怎么做的任何想法?

你可以使用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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM