【发布时间】:2014-04-21 04:24:47
【问题描述】:
从Concurrently run two functions that take parameters and return lists?,我可以通过指定 2 个队列并行运行 2 个函数。
from threading import Thread
from Queue import Queue
def func1(x):
return [i*i for i in x]
nums1 = [1,2,3,4,5]; nums2 = [112,32,53,64,25]
def wrapper(func, arg, queue):
queue.put(func(arg))
q1, q2 = Queue(), Queue()
Thread(target=wrapper, args=(func1, nums1, q1)).start()
Thread(target=wrapper, args=(func1, nums2, q2)).start()
print q1.get(), q2.get()
如何并行运行不同参数的相同函数的N个线程?
目前,我正在努力编码和做:
nums1 = [1,2,3,4,5]; nums2 = [112,32,53,64,25]
nums3 = [11,522,33,467,85]; nums4 = [12,2,5,4,1125]
q1, q2, q3, q4 = Queue(), Queue(), Queue(), Queue()
Thread(target=wrapper, args=(func1, nums1, q1)).start()
Thread(target=wrapper, args=(func1, nums2, q2)).start()
Thread(target=wrapper, args=(func1, nums3, q3)).start()
Thread(target=wrapper, args=(func1, nums4, q4)).start()
print q1.get(), q2.get(), q3.get()
【问题讨论】:
-
你可以使用来自多处理模块docs.python.org/2/library/…的pool.map
-
我有一个需要使用并行计算的问题。我尝试使用您提供的代码,然后我计划相应地修改我的代码。为了获得更长的计算时间,我将 nums1 和 nums2 替换为
range(100000)。我让其他一切都一样。当我运行脚本时,我意识到只有一个内核处于活动状态。我错过了什么吗?不应该是 2 个内核处于活动状态吗?
标签: python multithreading parallel-processing queue threadpool