zoukankan      html  css  js  c++  java
  • python 多进程-04 协程

    1. 协程是程序员创造出来的
    2. 单纯的协程没有作用
    3. 需要io操作时候进行切换 才有意义

    原理 greenlet

    import greenlet
    
    
    def f1():
        print(11)
        gr2.switch()
        print(33)
        gr2.switch()
    
    
    def f2():
        print(22)
        gr1.switch()
        print(44)
    
    
    if __name__ == '__main__':
        """
        1. 协程是程序员创造出来的
        2. 单纯的协程没有作用
        3. 需要io操作时候进行切换 才有意义
        """
        gr1 = greenlet.greenlet(f1)
        gr2 = greenlet.greenlet(f2)
    
        gr1.switch()
    

    协程常用模块 gevent

    from gevent import monkey
    monkey.patch_all()  # 以后代码中遇到IO都会自动执行greenlet 的 switch 进行切换
    import requests
    import gevent # 在money 之后导入
    
    def get_page(url):
        ret = requests.get(url)
        print(url, ret.content)
    
    
    if __name__ == '__main__':
        gevent.joinall([
            gevent.spawn(get_page, 'https://www.python.org'),
            gevent.spawn(get_page, 'https://www.baidu.com'),
            gevent.spawn(get_page, 'https://github.com'),
        ])
    
    
  • 相关阅读:
    Mac下安装brew
    Mac下安装node.js
    Mac下mysql服务端密码重置及环境配置
    Mac配置jdk以及maven
    Mac下卸载jdk
    34个漂亮的应用程序后台管理界面(系列一)
    ViewState
    get和post
    无刷新 分页评论
    isPostBack原理
  • 原文地址:https://www.cnblogs.com/pythonPath/p/12462786.html
Copyright © 2011-2022 走看看