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

Python 协程的应用场景

  •  
  •   a523 · Apr 12, 2019 · 5097 views
    This topic created in 2572 days ago, the information mentioned may be changed or developed.

    我掌握了 Python 的多线程编程, 也知道多进程 然而还有一个协程,也去学习了下, 也掌握一点协程的写法。 但是? Python 的协程的应用场景是? 一般的并发场景不都用线程,进程就解决了吗?我目前想不到什么场景适合用 Python 的协程比较好? 个人经验是用线程用的比较多,用在给不同主机批量发网络请求上。

    11 replies    2019-04-18 14:54:09 +08:00
    dobelee
        1
    dobelee  
       Apr 12, 2019 via Android
    只看功能不看性能系列?
    ipwx
        2
    ipwx  
       Apr 12, 2019
    1、协程比线程、进程处理 Network IO 要高效的多。也许可以 handle 高出一个数量级的客户端链接,不过我没有这方面的资料。
    2、Python 的多线程基本是废的,因为 GIL 的存在,所以只能用协程。
    mseasons
        3
    mseasons  
       Apr 13, 2019
    @ipwx 多线程可以用作 IO 密集的程序里
    Eds1995
        4
    Eds1995  
       Apr 13, 2019
    去看[faust]( https://github.com/robinhood/faust)源码,个人觉得是 python 里面用 asyncio 最完美的
    Eds1995
        5
    Eds1995  
       Apr 13, 2019
    676529483
        6
    676529483  
       Apr 13, 2019
    @ipwx 多线程在遇到 io 阻塞时,会释放 GIL,也不算完全费,只是达不到其他语言线程的效率
    fghjghf
        7
    fghjghf  
       Apr 13, 2019
    协程这玩意没啥用,线程的瓶颈就是他都瓶颈。他和线程都区别就是,线程都调度看系统,协程你可以自己控制。yield 就可以实现了
    keepeye
        8
    keepeye  
       Apr 13, 2019
    最常见的应用就是 web 服务器吧,比如 tornado

    我自己的话有一个场景,每个登录用户定时拉取外部信息的需求,如果每个用户开一个线程开销太大,所以就用协程还是很方便的
    lowman
        9
    lowman  
       Apr 16, 2019
    @mseasons python 的多线程基本是废的? 个人觉得有待商榷, 这里是否应该分场景讨论更合适, IO 密集型的任务使用 Python 的多线程去处理, 应该是可以实现多任务的, 一刀切应该并不合适
    mseasons
        10
    mseasons  
       Apr 16, 2019
    @lowman 你艾特错了呀……不是我说的
    jesnridy
        11
    jesnridy  
       Apr 18, 2019
    对于网络 IO 用协程处理不是美滋滋
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3198 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 53ms · UTC 13:41 · PVG 21:41 · LAX 06:41 · JFK 09:41
    ♥ Do have faith in what you're doing.