Python 多处理池获取整数识别调用

Python multiprocessing pool get integer identifying call

import multiprocessing

    def func():
        # Print call index
        pass

    p = multiprocessing.Pool(4)
    p.map(func, data)

在上面的代码中,是否可以在func()中打印一个整数,标识它被调用的次数0、1...

我想这样做是因为 func() 中有一些代码我只想执行一次,并且不能将其移出 func()

您想要做的涉及在进程之间共享状态——这在 Python 中可能会变得非常棘手。如果您不认为您可以重构您的程序来避免它,multiprocessing 具有来自 threading 模块的大部分有用的同步构造:https://docs.python.org/2/library/multiprocessing.html#synchronization-between-processes。听起来您可能需要一把锁和一些共享内存。