栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Python多处理和共享计数器

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python多处理和共享计数器

问题在于该

counter
变量未在您的进程之间共享:每个单独的进程都在创建它自己的本地实例并对其进行递增。

有关可用于在进程之间共享状态的某些技术,请参阅文档的本部分。在您的情况下,您可能希望

Value
在工作人员之间共享一个实例

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

from multiprocessing import Pool, Valuefrom time import sleepcounter = Nonedef init(args):    ''' store the counter for later use '''    global counter    counter = argsdef 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 * 10if __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()


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/414587.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号