如何使用python中的多进程池从不同的类(不同的模块)调用方法?在
我的目标是启动一个进程,该进程将一直运行到某个任务被提供,并且一旦任务完成,它将再次回到等待模式。在
下面是代码,它有三个模块,Reader类是我的运行时任务,我将向ProcessExecutor提供Reader方法的执行。
进程执行器是进程池,它将继续while循环,直到向它提供一些任务为止。在
启动一切的主模块。在Module 1
class Reader(object):
def __init__(self, message):
self.message = message
def reader(self):
print self.message
Module 2
class ProcessExecutor():
def run(self, queue):
print 'Before while loop'
while True:
print 'Reached Run'
try:
pair = queue.get()
print 'Running process'
print pair
func = pair.get('target')
arguments = pair.get('args', None)
if arguments is None:
func()
else:
func(arguments)
queue.task_done()
except Exception:
print Exception.message
main Module
from process_helper import ProcessExecutor
from reader import Reader
import multiprocessing
import Queue
if __name__=='__main__':
queue = Queue.Queue()
myReader = Reader('Hi')
ps = ProcessExecutor()
pool = multiprocessing.Pool(2)
pool.apply_async(ps.run, args=(queue, ))
param = {'target': myReader.reader}
queue.put(param)Code executed without any error: C:\Python27\python.exe
C:/Users/PycharmProjects/untitled1/main/main.py
Process finished with exit code 0
代码被执行,但它从未到达运行方法。我不确定是否可以使用多进程调用不同类的方法
我尝试了apply_async、map、apply,但都没有起作用。
所有在线搜索的示例都是从实现main方法的脚本调用target方法。
我使用的是python2.7
请帮忙。在