python中的协程

 1 import time
 2 import os
 3 
 4 def consumer():
 5     r = ''
 6     while True:
 7         n = yield r
 8         if not n:
 9             return
10         print('[CONSUMER] Consuming %s...' % n)
11         time.sleep(1)
12         print 'hello',os.getpid()
13         r = '200 OK'
14 
15 
16 def produce(c):
17     c.next()
18     n = 0
19     while n < 5:
20         n = n + 1
21         print('[PRODUCER] Producing %s...' % n)
22         r = c.send(n)
23         print('[PRODUCER] Consumer return: %s' % r)
24         print 'good',os.getpid()
25     c.close()
26 
27 if __name__=='__main__':
28     c = consumer()
29     produce(c)

执行结果:

原文地址:https://www.cnblogs.com/liunnis/p/4617712.html