http://www.cnblogs.com/linhaifeng/articles/7429894.html
进程与线程都是抢占式的
协程对应的是协作,非抢占式的
优势:没有切换的消耗,没有锁的概念
协程本质上就是一个线程,不能用多核,多进程 + 协程 是一个很好的解决方案
协程主要解决的也是IO操作
yield(协程)
def f(): print(1) yield 1 # 相当于return 只不过yield还可以返回函数继续调用 print(2) s = yield # 接收send的值 print(s) yield print(3) yield g = f() print(g) # <generator object f at 0x00000162B6CF7F10> ret = next(g) # 1 print(ret) # 1 next(g) # 2 g.send(50) g.__next__() # 3 #g.__next__() # StopIteration
yeild实现简单的协程例子
import time def constomer(name): print("%s ready to eat..." %name) while True: cake = yield print("[%s] is eating cake %s" %(name, cake)) def producer(): r1 = con1.__next__() r2 = con2.__next__() n = 0 while 1: time.sleep(1) print("\033[32;1mProduce\033[0m") con1.send(n) con2.send(n + 1) n += 2 if __name__ == "__main__": con1 = constomer("A君") con2 = constomer("B君") producer() ''' A君 ready to eat... B君 ready to eat... Produce [A君] is eating cake 0 [B君] is eating cake 1 Produce [A君] is eating cake 2 [B君] is eating cake 3 Produce [A君] is eating cake 4 [B君] is eating cake 5 '''
greenlet的switch