python_day10 协程 Greenlet
reenlet是一个用C实现的协程模块,相比与python自带的yield,它可以使你在任意函数之间随意切换,而不需把这个函数先声明为generator
from greenlet import greenlet def test1(): print('test1,first') gr2.switch() print('test1,sencod') gr2.switch() def test2(): print('test2,first') gr1.switch() print('test2,sencod') gr1=greenlet(test1) gr2=greenlet(test2) gr1.switch()
单纯的切换(在没有io的情况下或者没有重复开辟内存空间的操作),反而会降低程序的执行速度
#顺序执行 import time def f1(): res=0 for i in range(10000000): res+=i def f2(): res=0 for i in range(10000000): res*=i start_time=time.time() f1() f2() stop_time=time.time() print('run time is: %s' %(stop_time-start_time)) #1.7395639419555664 #切换 from greenlet import greenlet import time def f1(): res=0 for i in range(10000000): res+=i gr2.switch() def f2(): res=0 for i in range(10000000): res*=i gr1.switch() gr1=greenlet(f1) gr2=greenlet(f2) start_time=time.time() gr1.switch() stop_time=time.time() print('run time is: %s' %(stop_time-start_time)) #7.789067983627319
greenlet只是提供了一种比generator更加便捷的切换方式,仍然是没有解决遇到IO自动切换的问题