2012-03-21 41 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

相关问题