简单介绍协程

 1 #!/usr/bin/env python
 2 #-*-coding:utf-8 -*-
 3 
 4 '''
 5 协程: 协作式(线程、进程的切换都是抢占式)----------非抢占式
 6        协作式不代表没有切换,只是什么时候切换,完全在于我们自己的需求,因此协程的关键点也是什么时候切换。
 7         yield(协程) ,yield相当于一个临时的return,下次还可以在进来
 8 
 9 先理解生成器,yield,next,send,
10 回顾一下:有yield的函数是创建生成器,想调用需要.next或者__next__,send是往函数了发东西,函数了卡主的yield接收
11 
12 yield属于最底层的协程切换,Python有模块greenlet
13 '''
14 
15 # import time
16 #
17 # def consumer(name):
18 #
19 #     print("--->ready to eat baozi...")
20 #     while True:
21 #         new_baozi = yield
22 #         print("[%s] is eating baozi %s" % (name,new_baozi))
23 #         time.sleep(1)
24 #
25 # def producer():
26 #
27 #     r = con.__next__()
28 #     r = con2.__next__()          # 这里运行了consumer,但是consumer函数会到new_baozi = yield卡住,因为它在等待接收send发送的数据
29 #
30 #     n = 0
31 #     while 1:
32 #         time.sleep(1)
33 #         print("33[32;1m[producer]33[0m is making baozi %s and %s" %(n,n+1) )
34 #         con.send(n)
35 #         con2.send(n+1)
36 #         n +=2
37 #
38 #
39 # if __name__ == '__main__':
40 #
41 #     con = consumer("c1")
42 #     con2 = consumer("c2")         # 单单这两行,consumer里面的print是不会打印的,因为它只是产生生成器
43 #     producer()
44 
45 
46 ########################################################################################################################
47 ########################################################################################################################
48 
49 from greenlet import greenlet
50 
51 def test1():
52     print(12)
53     gr2.switch()
54     print(34)
55 def test2():
56     print(56)
57     gr1.switch()
58     print(78)
59     gr1.switch()
60 
61 gr1 = greenlet(test1)                    # 用模块greenlet封装函数test1
62 gr2 = greenlet(test2)
63 gr2.switch()                             # (切换)运行gr2
原文地址:https://www.cnblogs.com/maxiaonong/p/9538568.html