gevent是python的一個並發框架,采用協程實現並發目的,用起來也非常簡單
gevent的docs:http://www.gevent.org/contents.html
一個最簡單的例子:
import gevent import gevent.monkey gevent.monkey.patch_all() def foo(i, a, b, c): print('Running in foo' + str(i) + ' ' + str(a) + str(b) + str(c)) gevent.sleep(0) print('Explicit context switch to foo again') tasks = [ gevent.spawn(foo,i, 1, 2,3) for i in range(0,10)] gevent.joinall(tasks)
其中,
gevent.monkey.patch_all()的作用是將一些常見的阻塞,如socket、select等會阻塞的地方實現協程跳轉,而不是在那里一直等待,導致整個協程組無法工作。