协程
线程和进程的操作是由程序触发系统接口,最后的执行者是系统;协程的操作则是程序员。
协程存在的意义:对于多线程应用,CPU通过切片的方式来切换线程间的执行,线程切换时需要耗时(保存状态,下次继续)。协程,则只使用一个线程,在一个线程中规定某个代码块执行顺序。
协程的适用场景:当程序中存在大量不需要CPU的操作时(IO),适用于协程;
greenlet
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | #!/usr/bin/env python # -*- coding:utf-8 -*- from greenlet import greenlet def test1(): print 12 gr2.switch() print 34 gr2.switch() def test2(): print 56 gr1.switch() print 78 gr1 = greenlet(test1) gr2 = greenlet(test2) gr1.switch() |
gevent
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | import gevent def foo(): print ( 'Running in foo' ) gevent.sleep( 0 ) print ( 'Explicit context switch to foo again' ) def bar(): print ( 'Explicit context to bar' ) gevent.sleep( 0 ) print ( 'Implicit context switch back to bar' ) gevent.joinall([ gevent.spawn(foo), gevent.spawn(bar), ]) |
遇到IO操作自动切换:
![](https://images2015.cnblogs.com/blog/578419/201603/578419-20160317184011349-963859788.png)
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.python.org/'), gevent.spawn(f, 'https://www.yahoo.com/'), gevent.spawn(f, 'https://github.com/'), ])