如何使用“ for”循环实现多线程?

时间:2019-03-02 00:33:51

标签: python python-3.x multithreading

相似的问题以前可能已经问过几次,但是似乎没有我的案例/方案,或者它们都不起作用。

我正在尝试对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)

这应该遍历数组,并使用变量dosomething,然后依次是ab等来执行函数c

关于我该怎么做的任何想法?

1 个答案:

答案 0 :(得分:4)

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