V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
推荐学习书目
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
ALLROBOT
V2EX  ›  Python

请教 asyncio 生产-消费函数使用互斥锁保护 queue 共享资源

  •  
  •   ALLROBOT · Mar 10, 2023 · 2226 views
    This topic created in 1146 days ago, the information mentioned may be changed or developed.

    如题,库函数看的累人,希望有人口语化解释一下

    python 3.8.0

    1. 使用 semaphore 控制并发访问资源,并发访问网络资源并保存到本地,问了 chatgpt ,它说如果获取网页资源后,在 queue.put(xx)或 queue.get()之前不加 asyn with lock ,生产函数可能会覆盖队列中的数据、或者几个消费函数争抢同一个数据?

    实际测试,不管加不加锁,生产函数没有覆盖数据的情况,消费函数们各拿各自的,没有多个消费函数拿同一个队列同一个数据的情况,实际情况怎么样就不清楚了

    那么,有必要加锁给消费函数获得独占 queue 的访问权限,确保仅有一个消费函数只拿一个数据,这样会防止数据竞争的问题?

    1. 使用 semaphore>=2 的情况下,算是多个生产函数往 queue 添加数据吗?

    chatgpt 回答自相矛盾,说用semaphore的情景下,能保护共享资源不会发生数据争抢。。。我问既然用semaphore那有必要用asyn with lock么,它答如果不加锁会导致访问共享资源产生的一些问题。。。

    6 replies    2023-03-13 10:03:47 +08:00
    ruanimal
        1
    ruanimal  
       Mar 10, 2023
    queue 是线程安全的
    raymanr
        2
    raymanr  
       Mar 10, 2023
    没用过 semaphore, 不过感觉没必要给 queue 加锁吧
    copper20
        3
    copper20  
       Mar 10, 2023   ❤️ 1
    1. chatgpt 说话信一半就行了
    2. py 的 queue 本身都是多线程安全的,queue.Queue 用 mutex 实现,queue.SimpleQueue 用 semaphore 实现
    3. 使用 semaphore>=2 的情况下,算是多个生产函数往 queue 添加数据,但是因为 queue 本身多线程安全,所以问题不大
    4. semaphore 和 mutex 可以认为是对于一组资源的不同保护策略,针对一组资源一般只用一种策略
    zzl22100048
        4
    zzl22100048  
       Mar 10, 2023
    asyncio 的 queue 不需要锁,本身就是协程安全的
    ALLROBOT
        5
    ALLROBOT  
    OP
       Mar 10, 2023 via Android
    @zzl22100048 @ruanimal @copper20 明白了,感谢解惑
    ruanimal
        6
    ruanimal  
       Mar 13, 2023
    别把 chatgpt 的话当真,v2ex 现在这种情况很多。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3786 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 41ms · UTC 10:31 · PVG 18:31 · LAX 03:31 · JFK 06:31
    ♥ Do have faith in what you're doing.