首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python3池异步进程|工作进程

Python3池异步进程|工作进程
EN

Stack Overflow用户
提问于 2016-03-01 03:19:09
回答 1查看 886关注 0票数 0

我正在尝试使用4个进程的4个异步方法。

下面是我的1异步方法(X)的代码:

代码语言:javascript
复制
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类

代码语言:javascript
复制
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()
EN

回答 1

Stack Overflow用户

发布于 2016-03-01 04:04:38

multiprocessing.Pool被设计为一种将工作分配给一群工作人员的便捷方法,而无需担心哪个工作人员做哪项工作。它有大小的原因是允许您懒于将工作分派到队列的速度,并限制创建子进程的昂贵(相对)开销。

因此,您的问题的答案是原则上您不应该能够访问池中的单个工作人员。如果您希望能够单独寻址工人,则需要实现您自己的工作分配系统并使用multiprocessing.Process,例如:

代码语言:javascript
复制
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会帮你做到这一点,除非你有很好的证据证明你的情况出于某种原因而不是这样。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35707757

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档