协程原理:
def go(): print(1) yield(1) #生成器 print(11) yield(11) print(111) yield (111) my=go() #分段执行 print(type(my)) print(next(my))
协程案例切换:
import greenlet import time def go1(): while True: print("我是小明,雪糕我吃一口") gr2.switch() time.sleep(1) def go2(): while True: print("我是李娜,雪糕我吃一口") gr1.switch() time.sleep(1) if __name__=="__main__": gr1=greenlet.greenlet(go1) gr2=greenlet.greenlet(go2) gr1.switch()
协程开发:
import gevent import time """ #执行完需要30秒 showwait("王一",10) showwait("李二",10) showwait("张三",10) """ def showwait(name,n): #name代表名字 #n代表几秒 for i in range(n): print(name,"等待了",i+1,"秒") gevent.sleep(1) #不需要等待就顺序执行,需要等待,自动切换 g1=gevent.spawn(showwait,"庞子卓",10) g2=gevent.spawn(showwait,"韩海飞",10) g3=gevent.spawn(showwait,"李海宝",10) g1.join() #表示加入协程 g2.join() g3.join()
协程网络下载:
import gevent import gevent.monkey import urllib.request gevent.monkey.patch_all() #自动切换 def download(url): print("start",url) data=urllib.request.urlopen(url).read() print("length",len(data),url) #打印源代码的长度,并显示url #创建一个列表,加载多个任务, #gevent.joinall 表示全部加入协程 gevent.joinall([gevent.spawn(download,"http://www.baidu.com"), gevent.spawn(download,"http://www.163.com"), gevent.spawn(download,"http://www.qq.com"), gevent.spawn(download,"http://www.sina.com"), ])