V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
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 · 2021-11-02 19:51:17 +08:00 · 1798 次点击
    这是一个创建于 877 天前的主题,其中的信息可能已经有所发展或是发生改变。

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

    例如:

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

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

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

    你这场景, 队列吧, 虽然我自己都没怎么用过多进程的队列或者 manager 那些...
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1062 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 19:02 · PVG 03:02 · LAX 12:02 · JFK 15:02
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.