Python 协程

1.yield下的协程

 1 def consumer(name):
 2     print("--->starting...")
 3     while True:
 4         new_baozi = yield
 5         print("[%s] is eating baozi %s" % (name, new_baozi))
 6         # time.sleep(1)
 7 def producer():
 8     next(con)
 9     next(con2)
10     n = 0
11     while n < 5:
12         n += 1
13         con.send(n)
14         con2.send(n)
15         print("\033[32;1m[producer]\033[0m is making baozi %s" % n)
16 if __name__ == '__main__':
17     con = consumer("c1")
18     con2 = consumer("c2")
19     p = producer()
20 
21 '''
22 --->starting...
23 --->starting...
24 [c1] is eating baozi 1
25 [c2] is eating baozi 1
26 [producer] is making baozi 1
27 [c1] is eating baozi 2
28 [c2] is eating baozi 2
29 [producer] is making baozi 2
30 [c1] is eating baozi 3
31 [c2] is eating baozi 3
32 [producer] is making baozi 3
33 [c1] is eating baozi 4
34 [c2] is eating baozi 4
35 [producer] is making baozi 4
36 [c1] is eating baozi 5
37 [c2] is eating baozi 5
38 [producer] is making baozi 5
39 '''

2.greenlet下的协程

 1 #__author: Lobin
 2 #__date:   2018/1/25
 3 from greenlet import greenlet
 4 def test1():
 5     print(12)
 6     gr2.switch()
 7     print(34)
 8     gr2.switch()
 9 def test2():
10     print(56)
11     gr1.switch()
12     print(78)
13 gr1 = greenlet(test1)
14 gr2 = greenlet(test2)
15 gr1.switch()
16 
17 '''
18 12
19 56
20 34
21 78
22 '''

3.gevent 下的协程

 1 import gevent
 2 import time
 3 def func1():
 4     print('\033[31;1m李闯在跟海涛搞...\033[0m',time.ctime())
 5     gevent.sleep(2)
 6     print('\033[31;1m李闯又回去跟继续跟海涛搞...\033[0m',time.ctime())
 7 def func2():
 8     print('\033[32;1m李闯切换到了跟海龙搞...\033[0m',time.ctime())
 9     gevent.sleep(1)
10     print('\033[32;1m李闯搞完了海涛,回来继续跟海龙搞...\033[0m',time.ctime())
11 gevent.joinall([
12     gevent.spawn(func1),
13     gevent.spawn(func2),
14 ])
15 '''
16 李闯在跟海涛搞... Thu Jan 25 22:43:12 2018
17 李闯切换到了跟海龙搞... Thu Jan 25 22:43:12 2018
18 李闯搞完了海涛,回来继续跟海龙搞... Thu Jan 25 22:43:13 2018
19 李闯又回去跟继续跟海涛搞... Thu Jan 25 22:43:14 2018
20 '''

4.

 1 from gevent import monkey;
 2 monkey.patch_all()
 3 import gevent
 4 from urllib.request import urlopen
 5 def f(url):
 6     print('GET: %s' % url)
 7     resp = urlopen(url)
 8     data = resp.read()
 9     print('%d bytes received from %s.' % (len(data), url))
10 gevent.joinall([
11     gevent.spawn(f, 'https://www.python.org/'),
12     gevent.spawn(f, 'https://www.yahoo.com/'),
13     gevent.spawn(f, 'https://github.com/'),
14 ])
15 '''
16 GET: https://www.python.org/
17 GET: https://www.yahoo.com/
18 GET: https://github.com/
19 48893 bytes received from https://www.python.org/.
20 498526 bytes received from https://www.yahoo.com/.
21 52215 bytes received from https://github.com/.
22 '''

 

posted on 2018-01-25 23:23  可爱的春哥  阅读(94)  评论(0)    收藏  举报

导航