我有一套长期存在的流程,其中包含非常昂贵的设置,我希望将其推入一系列工作流程,以便并行完成工作。每个工人都是不同的,从我们数据库的不同部分构建。我会偶尔关闭工人并重建他们,比如说每4个小时左右。
我见过的用于多处理模块的python示例似乎是完全相同的,短暂的进程,只执行一次然后退出。
这是我提出的一个样本,用于将工作分发给一群不同的,长寿的工人。
这是正常的,还是有更好的方法来做到这一点?
class Worker(Process):
def __init__(self):
Process.__init__(self) # ...or super
self.parent_side, self.pipe = Pipe()
def do_super_slow_initialization(self):
print 'all work and no play makes Jack a dull boy'
def run(self):
self.do_super_slow_initialization()
while True:
message = self.pipe.recv()
if not message:
break
self.pipe.send({'message': message,
'pid': os.getpid(),
'ppid': os.getppid()
})
self.pipe.close()
def main():
print '+++ (parent)', os.getpid(), os.getppid()
workers = [Worker() for _ in xrange(10)]
# start the workers
for w in workers:
w.start()
# a bunch of messages to get through
for x in xrange(10):
# send message to each worker
for y, w in enumerate(workers):
w.parent_side.send('work%s_%s' % (x, y))
# get the results
for w in workers:
print w.parent_side.recv()
# shut down
for w in workers:
w.parent_side.send(None)
w.join()