Gevent 是一個第三方庫,可以輕鬆通過gevent實現併發同步或非同步編程 ...
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)