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
dafsic
V2EX  ›  Python

Python 协程间同步问题

  •  
  •   dafsic · 2019-10-09 12:59:21 +08:00 · 3830 次点击
    这是一个创建于 1632 天前的主题,其中的信息可能已经有所发展或是发生改变。

    可能是写 go 写多了,python3 用 asyncio,就一直想着把多个协程的结果写到一个 queue 里,然后再一个协程从 queue 里读数据处理,这种模式。 python3 刚学没多久,见识少,有谁知道异步 python 代码,有没有官方的最佳实践,有相应的项目链接就行,谢了。

    5 条回复    2019-10-11 17:54:59 +08:00
    Vegetable
        1
    Vegetable  
       2019-10-09 13:03:18 +08:00   ❤️ 1
    python3 的协程间都是共享的,你直接用一个列表就行了,都单线程的,共享内存
    StevanStark
        2
    StevanStark  
       2019-10-09 13:07:36 +08:00   ❤️ 1
    协程直接可以共享结果,直接传递结果
    wcsjtu
        3
    wcsjtu  
       2019-10-09 14:18:29 +08:00
    Python 协程同步, 也有 Lock、Queue、Condition 之类的, 没有的话,自己实现一个也很容易
    BBCCBB
        4
    BBCCBB  
       2019-10-09 14:23:19 +08:00
    asyncio.Queue. 不过默认没有 go channel 的 close 功能,
    sujin190
        5
    sujin190  
       2019-10-11 17:54:59 +08:00
    python 协程本来就是 future 调用链,单线程又是线程安全的,想实现 go 的 channel 逻辑很简单吧
    用两个变量,一个数组一个 await 等待对象,处理协程运行的时候判断下数组为空则创建一个 future 对象赋值给 await,然后等待 await 对象激活,数据协程则先往数据组中存入数据,判断下 await 对象存在且未激活就激活 await 对象,这时候处理协程就返回开始运行,取出数组数据处理就完了
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1066 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 22:44 · PVG 06:44 · LAX 15:44 · JFK 18:44
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.