zoukankan      html  css  js  c++  java
  • 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)


  • 相关阅读:
    bzoj2018 [Usaco2009 Nov]农场技艺大赛
    2014.9.27模拟赛【栅栏迷宫】
    cf471B MUH and Important Things
    cf471A MUH and Sticks
    bzoj3016 [Usaco2012 Nov]Clumsy Cows
    bzoj3404 [Usaco2009 Open]Cow Digit Game又见数字游戏
    bzoj1633 [Usaco2007 Feb]The Cow Lexicon 牛的词典
    bzoj3299 [USACO2011 Open]Corn Maze玉米迷宫
    codevs1040 统计单词个数
    codevs1039 数的划分
  • 原文地址:https://www.cnblogs.com/cansun/p/8401419.html
Copyright © 2011-2022 走看看