• python:协程


    #协程,又称为微线程,是一种用户态的轻量级线程
    #!usr/bin/env python
    # -*- coding:utf-8 -*-

    __author__ = "Samson"
    #greenlet是协程"手动挡切换"
    from greenlet import greenlet

    def test1():
    print(12)
    t2.switch()#切换到协程t2
    print(36)
    t2.switch()

    def test2():
    print(48)
    t1.switch()
    print(60)

    t1 = greenlet(test1)#启动一个协程
    t2 = greenlet(test2)

    t1.switch()



    #!usr/bin/env python
    # -*- coding:utf-8 -*-

    __author__ = "Samson"
    #greenlet是协程"自动挡切换"
    import gevent

    def foo():
    print("Running in foo")
    gevent.sleep(2)#模仿io操作
    print("Explicit context switch to foo again")


    def bar():
    print("Explicit精确的 context内容 to bar")
    gevent.sleep(1) # 模仿io操作
    print("Implicit context switch back to bar")

    gevent.joinall([
    gevent.spawn(foo),
    gevent.spawn(bar),
    ])


    协程之爬虫
    #!usr/bin/env python
    # -*- coding:utf-8 -*-

    __author__ = "Samson"

    from urllib import request
    import gevent,time
    from gevent import monkey

    monkey.patch_all()#将当前所有程序io操作单独做上标记,这样才能用协程方式进行爬虫,否则将会是串行的

    def f(url):
    print("Get: %s" %url)
    resp = request.urlopen(url)
    data = resp.read()
    print("%d bytes received from %s."%(len(data),url))

    urls = ["https://www.python.org/",
    "https://www.yahoo.com/",
    "https://github.com/"]
    time_start = time.time()
    for url in urls:
    f(url)
    print("同步cost",time.time()-time_start)

    async_time_start = time.time()
    gevent.joinall([
    gevent.spawn(f,"https://www.python.org/"),
    gevent.spawn(f,"https://www.yahoo.com/"),
    gevent.spawn(f,"https://github.com/"),
    ])
    print("协程cost",time.time()-async_time_start)


  • 相关阅读:
    基于Html5的爱情主题网站–表白神器
    一个基于WebGL的仿真3D水池有逼真的水波纹效果
    一些纯css3写的公司logo
    IIS、SQL SERVER和VS的安装顺序
    SQL Server 2008 收缩日志 清空删除大日志文件
    判断SqlConnection连接是否关闭
    正则
    C# MD5加密字符串
    sqlServer MD5
    sqlserver 连接数
  • 原文地址:https://www.cnblogs.com/cansun/p/8401419.html
Copyright © 2020-2023  润新知