推荐学习书目
› Learn Python the Hard Way
Python Sites
› PyPI - Python Package Index
› http://diveintopython.org/toc/index.html
› Pocoo
值得关注的项目
› PyPy
› Celery
› Jinja2
› Read the Docs
› gevent
› pyenv
› virtualenv
› Stackless Python
› Beautiful Soup
› 结巴中文分词
› Green Unicorn
› Sentry
› Shovel
› Pyflakes
› pytest
Python 编程
› pep8 Checker
Styles
› PEP 8
› Google Python Style Guide
› Code Style from The Hitchhiker's Guide
keroppi
V2EX  ›  Python

使用 concurrent.futures 多进程, 如何在进程中更新一个公共全局变量?

  •  
  •   keroppi · Nov 2, 2021 · 2989 views
    This topic created in 1832 days ago, the information mentioned may be changed or developed.

    这个公共变量是个字典,进程中各自读取、更新作这个字典内的对应项,不会有进程同时操作同一个项,

    例如:

    dict_var = {
       "zhangsan":{
       		# some code
       },
       "lisi":{
       		# some code
       }
       # more items
    }
    
    # 进程 1 只会读取、更新 dict_var['zhangsan']
    # 进程 2 只会读取、更新 dict_var['lisi']
    
    9 replies  •  2021-11-04 21:04:22 +08:00
    aptx4689
    aptx4689
    Nov 2, 2021 via iPhone
    1
    自己加个锁?
    xiaofengchen
    xiaofengchen
    Nov 2, 2021
    2
    可以直接操作,在进程启动前声明 dict_var 就行

    缺点是,进程启动后,内部只看得到启动前的 dict_var 以及自己修改的部分,其它进程修改部分是不可见的。

    如果需要共享内存,参考 https://docs.python.org/zh-cn/3/library/multiprocessing.shared_memory.html
    keroppi
    keroppi
    OP
    Nov 2, 2021
    3
    @xiaofengchen 多谢多谢,看了眼,是 3.8 新版功能.难怪没印象,我去学习学习
    UN2758
    UN2758
    Nov 3, 2021
    4
    如果多个线程操作一个字典的不同字段,这可以分开成两个字典独立操作,最后合并到一起,为什么放到一起呢
    UN2758
    UN2758
    Nov 3, 2021
    5
    @UN2758 #4 线程->进程
    julyclyde
    julyclyde
    Nov 3, 2021
    6
    楼上说的对
    apake
    apake
    Nov 3, 2021
    7
    既然各个进程 读取更新属于 各自的 变量, 为什么要放在一个 dict 里面呢. 最后处理完在合并不行么?
    keroppi
    keroppi
    OP
    Nov 4, 2021
    8
    是的,考虑到这个,换成 redis 了,各自维护 hash 中的数据
    ClericPy
    ClericPy
    Nov 4, 2021
    9
    避免竞争的简单方法比如队列, 比如锁...

    你这场景, 队列吧, 虽然我自己都没怎么用过多进程的队列或者 manager 那些...
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   3518 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 30ms · UTC 10:10 · PVG 18:10 · LAX 02:10 · JFK 05:10
    ♥ Do have faith in what you're doing.