标签:app 用户 imp %s stop consumer port 用户态 event
协程:单线程下的并发。又称微线程。是用户态的轻量级线程,即协程是由用户程序自己控制调度的
要遇到IO才切。
比线程开销更小。
修改共享数据不用加锁
yield greenlet都无法做到遇到IO就切换
gevent 可以监控多个任务之间的IO,遇到IO切换到另一个任务。
yield:
#并发执行 import time def producer(): g=consumer() next(g) for i in range(10000000): g.send(i) def consumer(): while True: res=yield start_time=time.time() producer() stop_time=time.time() print(stop_time-start_time) #串行 import time def producer(): res=[] for i in range(10000000): res.append(i) return res def consumer(res): pass start_time=time.time() res=producer() consumer(res) stop_time=time.time() print(stop_time-start_time)
Greenlet:
#pip3 install greenlet from greenlet import greenlet import time def eat(name): print(‘%s eat 1‘ %name) #time.sleep(10) #遇到IO就不会自动切换了 g2.switch(‘egon‘) print(‘%s eat 2‘ %name) g2.switch() def play(name): print(‘%s play 1‘ %name ) g1.switch() print(‘%s play 2‘ %name ) g1=greenlet(eat) g2=greenlet(play) g1.switch(‘egon‘)
Gevent: 详见下一节
标签:app 用户 imp %s stop consumer port 用户态 event
原文地址:https://www.cnblogs.com/beallaliu/p/9192928.html