2013-08-22 87 views
4

我嘗試使用Python 2.7多處理包創建隊列列表。每個子流程都擁有一個單獨的隊列,並且有兩個任務:從自己的隊列獲取元素並將元素放置到其他子流程的隊列中。因此,每個子進程必須知道哪個隊列屬於它,這就是爲什麼我使用隊列列表的原因。使用隊列列表的Python多處理

我做的代碼如下:

mgr = multiprocessing.Manager() 

sharedQueueList = mgr.list() 

for i in xrange(num_processes): 
    sharedQueueList .append(mgr.Queue()) 

但是,我得到了以下錯誤消息:

**raise convert_to_error(kind, result)** 
RemoteError: 
--------------------------------------------------------------------------- 
Unserializable message: ('#RETURN', < Queue.Queue instance at 0x02AD3170 >) 
--------------------------------------------------------------------------- 

回答

3

父創建的Queue是清單,手幾把每個工人創作時間。每個工作人員將從其中一個隊列中取出作業,輸出到另一個隊列。

import logging, multiprocessing 

def myproc(arg): 
    return arg*2 

def worker(qlist): 
    logger = multiprocessing.get_logger() 
    logger.info('start') 
    while True: 
     job = qlist[0].get() 
     logger.info('got %s', job) 
     if job is None: 
      logger.info('exiting') 
      return 
     qlist[1].put(myproc(job)) 

logger = multiprocessing.log_to_stderr(
    level=logging.INFO, 
) 
logger.info('setup') 

numProcs = 3 
queueList = [ multiprocessing.Queue() for i in xrange(numProcs) ] 

# prefill with 3 jobs 
for num in range(3): 
    queueList[0].put(num) 
# signal end of jobs 
queueList[0].put(None) 

worker_p = multiprocessing.Process(
    target=worker, args=([queueList[0], queueList[1]],), 
    name='worker', 
) 
worker_p.start() 

worker_p.join() 

logger.info('done') 

實施例運行:

[INFO/MainProcess] setup 
[INFO/worker] child process calling self.run() 
[INFO/worker] start 
[INFO/worker] got 0 
[INFO/worker] got 1 
[INFO/worker] got 2 
[INFO/worker] got None 
[INFO/worker] exiting 
[INFO/worker] process shutting down 
[INFO/worker] process exiting with exitcode 0 
[INFO/MainProcess] done 
[INFO/MainProcess] process shutting down