协程的好处
协程相比线程切换操作不耗费资源,线程的切换需要保存和恢复上下文,并且每个线程都有自己的cache缓存,比较好性能
线程切换导致代码碎片化,每次都要判断是否要切换,
协程只需要把所有的操作弄到一起,有一个耗时操作就切换到下一个操作继续执行
线程的问题在于他不会主动触发调度器,尤其是cpu密集型的,没有io操作
协程的实现
greenlet模块和gevent模块
greenlet需要根据程序的设计,即认为的切换协程
gevent是有耗时操作自动切换
from gevent import monkey;
import gevent
import urllib2
#有IO才做时需要这一句
monkey.patch_all()
def myDownLoad(url):
print('GET: %s' % url)
resp = urllib2.urlopen(url)
data = resp.read()
print('%d bytes received from %s.' % (len(data), url))
gevent.joinall([
gevent.spawn(myDownLoad, 'http://www.baidu.com/'),
gevent.spawn(myDownLoad, 'http://www.itcast.cn/'),
gevent.spawn(myDownLoad, 'http://www.itheima.com/'),
])