简体   繁体   English

在多处理池进程中运行代码

[英]Run code in multiprocessing pool processes

How can I handle multiprocessing.Pool() error in initialization?如何处理初始化中的 multiprocessing.Pool() 错误?

In short, I use总之,我用
pool = multiprocessing.Pool(os.cpu_count(), initializer=init)

def init(): 
   # stop everything if that fails with exception
   # init..

Related question How to handle initializer error in multiprocessing.Pool?相关问题如何处理 multiprocessing.Pool 中的初始化错误?

But it does not show how to exit the main process cleanly.但它没有显示如何干净地退出主进程。

Is it possible to get each Process instance fromthe pool, and run a function in each of them?是否可以从池中获取每个Process实例,并在每个实例中运行一个函数? Note this is not the same as pool.map , because I don't know in which process my function will run.请注意,这与pool.map ,因为我不知道我的函数将在哪个进程中运行。

How about using a Queue to listen for initialisation failures?如何使用Queue来监听初始化失败?

For example:例如:

from multiprocessing import Pool, Manager
from random import random

# an initialisation function that fails 10% of the time
def init(initdone):
    try:
        # fail sometimes!
        assert random() < 0.9
    except Exception as err:
        # record the failure
        initdone.put(err)
    finally:
        # record that initialisation was successful
        initdone.put(None)

# we need a manager to maintain the queue
with Manager() as manager:
    # somewhere to store initialisation state
    initresult = manager.Queue()

    # number of workers we want to wait for
    nprocs = 5

    with Pool(nprocs, initializer=init, initargs=(initresult,)) as pool:
        # wait for initializers to run
        for i in range(nprocs):
            res = initresult.get()
            # reraise if it failed (or whatever logic is appropriate)
            if res is not None:
                raise res

        # do something now we've got this pool set up
        print(sum(pool.map(int, range(20))))

I should note that multiprocessing can restart failed workers, so you might get more than nprocs entries entered into the queue.我应该注意到multiprocessing可以重新启动失败的工作人员,因此您可能会获得超过nprocs条目进入队列。 In the OP's case this is probably OK as they said they wanted to abort in this case, but this might not be true in other situations.在 OP 的情况下,这可能没问题,因为他们说在这种情况下他们想中止,但在其他情况下可能并非如此。

I can't think of any ways in which you'd get less than nprocs entries in the queue, please comment if you see any!我想不出有什么方法可以让您在队列中获得少于nprocs条目,如果您看到任何条目,请发表评论! Note that I'm deliberately not catching BaseException in init as that's handled by code in multiprocessing (along with a few others) and it seems sensible to let it do the right thing.请注意,我故意没有在init捕获BaseException ,因为它是由multiprocessing处理中的代码(以及其他一些)处理的,让它做正确的事情似乎是明智的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM