2012-03-21 40 views
1

我試圖讓一些CPU綁定任務的多處理工作。但是,我無法弄清楚如何在子進程中調用一個函數,並可能傳入一些參數來執行帶外任務。任何幫助表示讚賞。如何調用一個函數並通過多處理傳遞一些參數

child.py

import multiprocessing 
def Performer(multiprocessing.Process): 

    def __init__(self, taks_queue): 
     super().__init__() 
     self.taks_queue = taks_queue 
     self.term_str = "done" 

    def set_term_str(self, term_str): 
     self.term_str = term_str 

    def run(self): 
     while True: 
      task = taks_queue.get() 
      if task == self.term_str: 
       while taks_queue.qsize() > 0: 
        taks_queue.get() 
      else:   
       handle_task(task) 

parent.py

import multiprocessing 
def Generator(multiprocessing.Process): 

    def run(self): 
     taks_queues = [multiprocessing.Queue(-1) for i in range(5)] 
     for i in range(5): 
      perfs.append(Performer(taks_queue = taks_queue[i])) 
      perfs[i].start() 

     while True: 
      message = get_message() 
      mod = check_message(message) 
      if mod != 0: 
       term_str = get_term_str(mod,message) 
       perfs[mod].set_term_str(term_str) 

      handle_task(task) 

if __name__=="__main__": 
    gen = Generator() 
    gen.start() 
    gen.join() 

發電機外界進行通信,並且需要在必要時改變長期的字符串。我將如何能夠調用另一個多處理的函數。處理並傳遞一些參數來改變多處理的執行行爲。

回答

0

你有2個主要選項:

  1. 使用價值()申報共享內存,可用雙方父母和孩子。您可以使用整數或字符串作爲共享值。請參閱http://docs.python.org/library/multiprocessing.html#shared-ctypes-objects

  2. 將term_string放入子項的任務隊列中。當孩子從隊列中彈出時,它需要檢查值。

BTW你想要的東西,蟒蛇已經提供了一個子進程工作池的偉大機制,見http://docs.python.org/library/multiprocessing.html#using-a-pool-of-workers

from multiprocessing import Pool 

def f(x): 
    return x*x 

if __name__ == '__main__': 
    pool = Pool(processes=4)    # start 4 worker processes 
    result = pool.apply_async(f, [10]) # evaluate "f(10)" asynchronously 
    print result.get(timeout=1)   # prints "100" unless your computer is *very* slow 
    print pool.map(f, range(10))   # prints "[0, 1, 4,..., 81]" 
+0

感謝您試用,但我會通過一些可拾取對象作爲參數,這樣共享記憶沒有幫助。池不適合,因爲我需要根據消息更改term_str,並且期望執行者在首次發送幾條消息之後會有不同的term_str。 – SCM 2012-03-21 23:32:59

+0

然後您必須通過隊列推送term_str。你不能在你的代碼中做你想做的事。 – 2012-03-21 23:34:31

相關問題