Python多处理与共享通信

2024-05-16 03:17:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我的多处理模块有问题。我正在使用一个带有map方法的workers池从许多文件中加载数据,并对每个文件使用一个自定义函数分析数据。每次处理一个文件时,我都想更新一个计数器,以便跟踪还有多少文件需要处理。 下面是示例代码:

def analyze_data( args ):
    # do something 
    counter += 1
    print counter


if __name__ == '__main__':

    list_of_files = os.listdir(some_directory)

    global counter
    counter = 0

    p = Pool()
    p.map(analyze_data, list_of_files)

我找不到解决办法。


Tags: 模块文件of数据方法函数示例map
3条回答

问题是counter变量在进程之间不共享:每个单独的进程都在创建自己的本地实例并递增该实例。

请参阅文档中的this section,了解可以用于在进程之间共享状态的一些技术。在您的情况下,您可能希望在工作人员之间共享一个^{}实例

下面是示例的工作版本(带有一些虚拟输入数据)。请注意,它使用了全局值,我在实践中会尽量避免:

from multiprocessing import Pool, Value
from time import sleep

counter = None

def init(args):
    ''' store the counter for later use '''
    global counter
    counter = args

def analyze_data(args):
    ''' increment the global counter, do something with the input '''
    global counter
    # += operation is not atomic, so we need to get a lock:
    with counter.get_lock():
        counter.value += 1
    print counter.value
    return args * 10

if __name__ == '__main__':
    #inputs = os.listdir(some_directory)

    #
    # initialize a cross-process counter and the input lists
    #
    counter = Value('i', 0)
    inputs = [1, 2, 3, 4]

    #
    # create the pool of workers, ensuring each one receives the counter 
    # as it starts. 
    #
    p = Pool(initializer = init, initargs = (counter, ))
    i = p.map_async(analyze_data, inputs, chunksize = 1)
    i.wait()
    print i.get()

没有竞争条件错误的计数器类:

class Counter(object):
    def __init__(self):
        self.val = multiprocessing.Value('i', 0)

    def increment(self, n=1):
        with self.val.get_lock():
            self.val.value += n

    @property
    def value(self):
        return self.val.value

更快的计数器类,无需使用内置的值锁两次

class Counter(object):
    def __init__(self, initval=0):
        self.val = multiprocessing.RawValue('i', initval)
        self.lock = multiprocessing.Lock()

    def increment(self):
        with self.lock:
            self.val.value += 1

    @property
    def value(self):
        return self.val.value

https://eli.thegreenplace.net/2012/01/04/shared-counter-with-pythons-multiprocessinghttps://docs.python.org/2/library/multiprocessing.html#multiprocessing.sharedctypes.Valuehttps://docs.python.org/2/library/multiprocessing.html#multiprocessing.sharedctypes.RawValue

相关问题 更多 >