3-2 greenlet module

A module greenlet

If we have 20 tasks within a single thread, in order to achieve switching between multiple tasks, using the yield Builder way too cumbersome (you need to get initialized once the generator, and then call the send ... very troublesome) , while using very simple greenlet module 20 to achieve this task is switched directly

#安装: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')#可以在第一次switch时传入参数,以后都不需要

Simple switch (in the absence of io situation or did not repeat the operation to open up memory space), but will reduce program execution speed

#顺序执行
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

#切换
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 only provides a more convenient way than the generator switch, when cut to the execution If you encounter a task io, blocking it in place, is still not solved the problems encountered IO automatically switches to improve efficiency.

In the single-threaded code for these 20 tasks usually calculated both operations have a blocking operation, we can go to perform the task 2 in task execution time experience blocking 1:00, on the use of obstruction. . . . So, in order to improve efficiency, which uses Gevent module.

Guess you like

Origin www.cnblogs.com/shibojie/p/11664813.html