File tree 2 files changed +44
-0
lines changed
2 files changed +44
-0
lines changed Original file line number Diff line number Diff line change @@ -9,6 +9,30 @@ yield 没有逻辑意义,仅是作为暂停的标志点。程序流可以在
9
9
通过轮转队列依次唤起任务,并将已经完成的任务清出队列,模拟任务调度的过程。
10
10
```
11
11
12
+ ### coroutine.py python通过gevent第三方库实现协程
13
+ ```
14
+ 上面的dispatch.py通过yield提供了对协程的支持,模拟了任务调度。而下面的这个gevent第三方库就更简单了。
15
+
16
+ 第三方的gevent为Python提供了比较完善的协程支持。通过greenlet实现协程,其基本思想是:
17
+ 当一个greenlet遇到IO操作时,比如访问网络,就自动切换到其他的greenlet,等到IO操作完成,再在适当的时候切换回来继续执行。
18
+ 由于IO操作非常耗时,经常使程序处于等待状态,有了gevent为我们自动切换协程,就保证总有greenlet在运行,而不是等待IO。
19
+
20
+ 由于切换是在IO操作时自动完成,所以gevent需要修改Python自带的一些标准库,这一过程在启动时通过monkey patch完成:
21
+
22
+ 依赖:
23
+ pip install gevent
24
+
25
+ 执行:
26
+ ➜ Py git:(master) ✗ python coroutine.py
27
+ GET: https://www.python.org/
28
+ GET: https://www.yahoo.com/
29
+ GET: https://github.com/
30
+ 91430 bytes received from https://github.com/.
31
+ 47391 bytes received from https://www.python.org/.
32
+ 461975 bytes received from https://www.yahoo.com/.
33
+
34
+ ```
35
+
12
36
13
37
### base64.py base64加密原理
14
38
```
Original file line number Diff line number Diff line change
1
+ # -*- coding: utf-8 -*-
2
+ # @Author: lock
3
+ # @Date: 2017-05-03 00:06:17
4
+ # @Last Modified by: lock
5
+ # @Last Modified time: 2017-05-03 00:06:22
6
+ from gevent import monkey ; monkey .patch_all ()
7
+ import gevent
8
+ import urllib2
9
+
10
+ def f (url ):
11
+ print ('GET: %s' % url )
12
+ resp = urllib2 .urlopen (url )
13
+ data = resp .read ()
14
+ print ('%d bytes received from %s.' % (len (data ), url ))
15
+
16
+ gevent .joinall ([
17
+ gevent .spawn (f , 'https://www.python.org/' ),
18
+ gevent .spawn (f , 'https://www.yahoo.com/' ),
19
+ gevent .spawn (f , 'https://github.com/' ),
20
+ ])
You can’t perform that action at this time.
0 commit comments