赞
踩
协程
即 Coroutine,又称微线程、纤程。单进程的异步编程模型称为协程。
由于IO过于耗时,协程可以在IO发生时把资源交给其他协程使用,IO结束时收回资源供自己使用。
from gevent import monkey;
monkey.patch_all()
import gevent
import urllib2
def f(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(f, 'https://www.httpbin.org/get?a=1'),
gevent.spawn(f, 'https://www.httpbin.org/get?a=2'),
gevent.spawn(f, 'https://www.httpbin.org/get?a=3')
])

打印结果是:
GET: https://www.httpbin.org/get?a=1
GET: https://www.httpbin.org/get?a=2
GET: https://www.httpbin.org/get?a=3
263 bytes received from https://www.httpbin.org/get?a=3.
263 bytes received from https://www.httpbin.org/get?a=2.
263 bytes received from https://www.httpbin.org/get?a=1.
版权声明:转载必须注明本文转自 East196 的博客:http://blog.csdn.net/east196
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。