[英]Multiprocessing Queues with python
我试图创建一个基本脚本来利用多处理来处理队列中充满对象并在每个对象上调用一个方法。
我了解多重处理和池等的原理。请参阅下面的内容:
from multiprocessing import Queue, Pool
from object import obj
import time
currentTime = time.time() #used to work out how long it takes for the script to complete
work_queue = Queue()
#create some objects to work with
a = obj('obj1')
b = obj('obj2')
#put them in the queue
work_queue.put(a)
work_queue.put(b)
def doFunction(q):
temp = q.get()
print temp.getVar()
if __name__ == '__main__':
pool = Pool(2) #Create a pool with two processes
pool.map(doFunction, work_queue, 1)
pool.close()
pool.join()
print time.time() - currentTime #prints out the time taken to run script
这将引发错误:
Traceback (most recent call last):
File "/home/adam/workspace/MultiProcessing/test2.py", line 35, in <module>
pool.map(doSNMP, work_queue, 1)
File "/usr/lib/python2.7/multiprocessing/pool.py", line 251, in map
return self.map_async(func, iterable, chunksize).get()
File "/usr/lib/python2.7/multiprocessing/pool.py", line 304, in map_async
iterable = list(iterable)
TypeError: 'Queue' object is not iterable
如果有人可以提供任何输入,我将不胜感激!
错误跟踪在问题上非常清楚。 这甚至让我感到惊讶,但是Queue确实不是可迭代的。
Queue
主要用于在流程之间进行通信。 但是您的代码只是要做一些事情并从中读取一些属性,因此没有太多需要交流的地方。
因此,我修改了您的代码。
Object
类型的项目。 保留使用pool.map
。 它生成可迭代的任务。
from multiprocessing import Queue, Pool
import time
class Obj(object):
def __init__(self, name):
self.name = name
def getVar(self):
return self.name
currentTime = time.time() #used to work out how long it takes for the script to complete
def jobgenerator(num):
for i in xrange(1, num+1):
yield Obj("obj"+str(i))
def doFunction(job):
time.sleep(1)
print job.getVar()
if __name__ == '__main__':
pool = Pool(2) #Create a pool with two processes
pool.map(doFunction, jobgenerator(10), 2)
pool.close()
pool.join()
print time.time() - currentTime #prints out the time taken to run script
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.