我正在尝试使用一些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()
生成器与外界通信,需要时更改术语字符串。我如何能够调用另一个multiprocessing.Process的函数并传递一些参数来改变multiprocessing.Process的执行行为?
答案 0 :(得分:0)
您有两个主要选择:
使用Value()声明共享内存,父内容和子代都可以使用。您可以使用整数或字符串作为共享值。见http://docs.python.org/library/multiprocessing.html#shared-ctypes-objects
将term_string放入子任务队列。当孩子从队列中弹出时,需要检查该值。
顺便提一下你想要的东西,python已经提供了子进程工作池的强大机制,请参阅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]"