Network Programming Module coroutine --gevent

Network Programming Module coroutine --gevent

gevent module

安装
pip3 install gevent

Gevent is a third-party library, you can easily implement synchronous or asynchronous concurrent programming by gevent, the main mode is used in gevent Greenlet, it is a form of access Python C extension module lightweight coroutines. Greenlet all run inside the main operating system processes, but they are collaboratively scheduling.

#用法
g1=gevent.spawn(func,1,,2,3,x=4,y=5)创建一个协程对象g1,spawn括号内第一个参数是函数名,如eat,后面可以有多个参数,可以是位置实参或关键字实参,都是传给函数eat的
g2=gevent.spawn(func2)
g1.join() #等待g1结束
g2.join() #等待g2结束
#或者上述两步合作一步:gevent.joinall([g1,g2])
g1.value#拿到func1的返回值

It will automatically switch tasks encountered blocking IO

import gevent
def eat(name):
    print('%s eat 1' %name)
    gevent.sleep(2)
    print('%s eat 2' %name)
def play(name):
    print('%s play 1' %name)
    gevent.sleep(1)
    print('%s play 2' %name)
g1=gevent.spawn(eat,'egon')
g2=gevent.spawn(play,name='egon')
g1.join()
g2.join()
#或者gevent.joinall([g1,g2])
print('主')

EXAMPLE upper gevent.sleep (2) is simulated gevent io recognizable obstruction, and time.sleep (2) or other obstruction, gevent is not directly recognize the need to use the following line, patch, it can be identified.

from gevent import monkey; monkey.patch_all () must be placed before those of the previous patch, such as time, socket module, or we simply remember to: use gevent, needs to be from gevent import monkey; monkey.patch_all () put to the beginning of the file.

from gevent import monkey;monkey.patch_all()
import gevent
import time
def eat():
    print('eat food 1')
    time.sleep(2)
    print('eat food 2')
def play():
    print('play 1')
    time.sleep(1)
    print('play 2')
g1=gevent.spawn(eat)
g2=gevent.spawn(play_phone)
gevent.joinall([g1,g2])
print('主')

Guess you like

Origin www.cnblogs.com/Kwan-C/p/11595885.html