master greenlet modular
The duration of this section needs to be controlled 5 Within minutes
If we have... In a single thread 20 A mission , To switch between multiple tasks , Use yield The generator is too cumbersome ( You need to get the generator initialized once first , Then call send... Very trouble ), While using greenlet Modules can do this very simply 20 Direct task switching
# install :pip3 install greenlet
from greenlet import greenlet
def eat(name):
print('%s eat 1' %name)
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’)# For the first time switch The parameter is passed in , No need for
Simple switching ( In the absence of io In case of or without repeated operation of opening memory space ), On the contrary, it will reduce the execution speed of the program
# Sequential execution
import time
def f1():
res=1
for i in range(100000000):
res+=i
def f2():
res=1
for i in range(100000000):
res*=i
start=time.time()
f1()
f2()
stop=time.time()
print('run time is %s' %(stop-start)) #10.985628366470337
# Switch
from greenlet import greenlet
import time
def f1():
res=1
for i in range(100000000):
res+=i
g2.switch()
def f2():
res=1
for i in range(100000000):
res*=i
g1.switch()
start=time.time()
g1=greenlet(f1)
g2=greenlet(f2)
g1.switch()
stop=time.time()
print('run time is %s' %(stop-start)) # 52.763017892837524
greenlet It just provides a comparison generator More convenient switching mode , When cutting to a task execution, if io, Then block in place , It's still not solved IO The problem of automatic switching to improve efficiency .
This one in a single thread 20 The code of tasks usually has both calculation and blocking operations , We could be on a mission 1 When there's a jam , Just use the blocked time to perform the task 2.... such , To improve efficiency , And that's where it comes in Gevent modular .
“ It is necessary to read thi