Gevent 是一个第三方库,可以轻松通过gevent实现并发同步或异步编程,在gevent中用到的主要模式是Greenlet, 它是以C扩展模块形式接入Python的轻量级协程。 Greenlet全部运行在主程序操作系统进程的内部,但它们被协作式地调度。
1 import gevent 2 3 def foo(): 4 print('Running in foo') 5 gevent.sleep(1) 6 print('Explicit context switch to foo again') 7 8 def bar(): 9 print('Explicit context to bar') 10 gevent.sleep(2) 11 print('Implicit context switch to bar again') 12 gevent.joinall([ 13 gevent.spawn(foo), 14 gevent.spawn(bar), 15 ])
1 from gevent import monkey; 2 3 monkey.patch_all() 4 from urllib.request import urlopen 5 import time 6 7 def f(url): 8 print('GET: %s' % url) 9 resp = urlopen(url) 10 data = resp.read() 11 print('%d bytes received from %s.' % (len(data), url)) 12 13 #l=['https://www.python.org/','https://www.baidu.com/','https://github.com/'] 14 start=time.time() 15 # for url in l: 16 # f(url) 17 18 gevent.joinall([ 19 gevent.spawn(f, 'https://www.python.org/'), 20 gevent.spawn(f, 'https://www.baidu.com/'), 21 gevent.spawn(f, 'https://github.com/'), 22 ]) 23 24 end=time.time() 25 print(end-start)