[英]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.