Python3池异步进程|工作人员

时间:2016-02-29 19:19:09

标签: python asynchronous

我正在尝试使用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 Pool中的参数进程是worker的数量。

我如何使用这些工人?

编辑:我的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()

1 个答案:

答案 0 :(得分:0)

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!')

现在您可以直接访问每个工作人员。如果您希望能够在每个工作人员运行时动态地将工作发送给每个工作人员(不仅仅是像我在我的示例中那样给一件事做),那么您必须自己实施,可能使用multiprocessing.Queue。查看multiprocessing的代码,了解该分发如何分配给其工作人员,以了解如何执行此操作。

你为什么要这样做呢?如果只关心工人是否能够有效地安排工作,那么我的建议就是信任multiprocessing以便为你做到这一点,除非你有充分的证据表明在你的情况下不适合某种原因。

相关问题