我正在尝试使用4个进程的4个异步方法。
下面是我的1异步方法(X)的代码:
from multiprocessing import Pool
import time
def x(i):
while(i < 100):
print(i)
i += 1
time.sleep(1)
def finish(str):
print("done!")
if __name__ == "__main__":
pool = Pool(processes=5)
result = pool.apply_async(x, [0], callback=finish)
print("start")根据:https://docs.python.org/2/library/multiprocessing.html#multiprocessing.JoinableQueue,池中的进程数参数是工作进程的数量。
我如何使用这些工人?
编辑:我的ASYNC类
from multiprocessing import Pool
import time
class ASYNC(object):
def __init__(self, THREADS=[]):
print('do')
pool = Pool(processes=len(THREADS))
self.THREAD_POOL = {}
thread_index = 0
for thread_ in THREADS:
self.THREAD_POOL[thread_index] = {
'thread': thread_['thread'],
'args': thread_['args'],
'callback': thread_['callback']
}
pool.apply_async(self.run, [thread_index], callback=thread_['callback'])
self.THREAD_POOL[thread_index]['running'] = True
thread_index += 1
def run(self, thread_index):
print('enter')
while(self.THREAD_POOL[thread_index]['running']):
print("loop")
self.THREAD_POOL[thread_index]['thread'](self.THREAD_POOL[thread_index])
time.sleep(1)
self.THREAD_POOL[thread_index]['running'] = False
def wait_for_finish(self):
for pool in self.THREAD_POOL:
while(self.THREAD_POOL[pool]['running']):
time.sleep(1)
def x(pool):
print(str(pool))
pool['args'][0] += 1
def y(str):
print("done")
A = ASYNC([{'thread': x, 'args':[10], 'callback':y}])
print("start")
A.wait_for_finish()发布于 2016-03-01 04:04:38
multiprocessing.Pool被设计为一种将工作分配给一群工作人员的便捷方法,而无需担心哪个工作人员做哪项工作。它有大小的原因是允许您懒于将工作分派到队列的速度,并限制创建子进程的昂贵(相对)开销。
因此,您的问题的答案是原则上您不应该能够访问池中的单个工作人员。如果您希望能够单独寻址工人,则需要实现您自己的工作分配系统并使用multiprocessing.Process,例如:
from multiprocessing import Process
def x(i):
while(i < 100):
print(i)
i += 1
pools = [Process(target=x, args=(1,)) for _ in range(5)]
map(lambda pool: pool.start(), pools)
map(lambda pool: pool.join(), pools)
print('Done!')现在,您可以直接访问每个工作进程。如果您希望能够在worker运行时动态地向每个worker发送工作(而不是像我在示例中那样只让它做一件事),那么您必须自己实现它,可能需要使用multiprocessing.Queue。看看multiprocessing的代码,看看它是如何将工作分配给它的工作人员的,从而了解如何做到这一点。
你为什么要这么做呢?如果只是关心员工的日程安排是否有效,那么我的建议是相信multiprocessing会帮你做到这一点,除非你有很好的证据证明你的情况出于某种原因而不是这样。
https://stackoverflow.com/questions/35707757
复制相似问题