Gem*_*ash 6 python multithreading python-3.x
之前可能已经问了几次类似的问题,但是它们似乎都没有我的案例/场景或它不起作用.
我试图多线程一个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)
Run Code Online (Sandbox Code Playgroud)
这应该通过数组循环并执行功能dosomething与变量a,那么b,c等等.
关于我怎么做的任何想法?
您可以使用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()
Run Code Online (Sandbox Code Playgroud)
5 秒内以随机顺序输出:
e
b
c
a
d
Run Code Online (Sandbox Code Playgroud)
如果你想限制线程数,你可以使用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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
103 次 |
| 最近记录: |