python 协程
协程
协程就是一种用户态内的上下文切换技术.
1.使用gevent实现协程, gevent.spawn()调用函数, gevent.sleep(1) 模拟阻塞,实现切换.
1 import gevent 2 import time 3 4 5 def foo(): 6 print('running in foo',time.ctime()) 7 gevent.sleep(1) 8 print('Explicit context switch to foo again',time.ctime()) 9 10 11 def bar(): 12 print('running in foo', time.ctime()) 13 gevent.sleep(2) 14 print('EIxplicit context switch to foo again', time.ctime()) 15 16 gevent.joinall([ 17 gevent.spawn(foo), 18 gevent.spawn(bar) 19 ])
2.协程可以实现高并发,且占用的资源比进程和线程少.
1 #!/usr/bin/env python3 2 # -*- coding=utf-8 -*- 3 from gevent import monkey 4 import gevent 5 monkey.patch_all() #刷新 6 from urllib.request import urlopen 7 import time 8 9 def f(url): 10 print('get:%s'%url) 11 resp=urlopen(url) 12 data=resp.read() 13 print('%d bytes received from %s .' %(len(data),url)) 14 15 l=['http://www.xiaohuar.com/hua/','http://www.zhihu.com/question/21653286','http://news.dahe.cn/2016/10-12/107590869.html'] 16 start=time.time() 17 18 #协程方式 19 gevent.joinall([ 20 gevent.spawn(f,'http://www.xiaohuar.com/hua/'), 21 gevent.spawn(f,'http://www.zhihu.com/question/21653286'), 22 gevent.spawn(f,'http://news.dahe.cn/2016/10-12/107590869.html') 23 ]) 24 25 #普通方式 26 # for url in l: 27 # f(url) 28 29 print(time.time()-start)