python 并发编程 协程 gevent模块
一 gevent模块
gevent应用场景:
单线程下,多个任务,io密集型程序
安装
pip3 install gevent
Gevent 是一个第三方库,可以轻松通过gevent实现并发同步或异步编程,在gevent中用到的主要模式是Greenlet, 它是以C扩展模块形式接入Python的轻量级协程。 Greenlet全部运行在主程序操作系统进程的内部,但它们被协作式地调度。
gevent可以检测io,实现遇到io自动切换另外一个任务
#用法
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的返回值
遇到io立刻 切换到另外一个任务,这是使用gevent.sleep 自己产生的io操作
import gevent import time def eat(name): print("%s:eat 1" %name) gevent.sleep(3) print("%s:eat 2" %name) def play(name): print("%s:play 1" % name) gevent.sleep(4) print("%s:play 2" % name) g1 = gevent.spawn(eat,"mike") g2 = gevent.spawn(play,"mike") start_time = time.time() g1.join() g2.join() end_time = time.time() print(end_time-start_time) ''' mike:eat 1 mike:play 1 mike:eat 2 mike:play 2 4.0012290477752686 '''
而time.sleep(2)或其他的阻塞,gevent是不能直接识别的,遇到io不切换另外一个任务
gevent模块 只能识别自己模拟的io操作,其他io操作无法识别
import gevent import time def eat(name): print("%s:eat 1" %name) time.sleep(3) print("%s:eat 2" %name) def play(name): print("%s:play 1" % name) time.sleep(4) print("%s:play 2" % name) g1 = gevent.spawn(eat,"mike") g2 = gevent.spawn(play,"mike") start_time = time.time() g1.join() g2.join() end_time = time.time() print(end_time-start_time) ''' mike:eat 1 mike:eat 2 mike:play 1 mike:play 2 7.0004003047943115 '''
需要用下面一行代码,打补丁,就可以识别了,
from gevent import monkey;monkey.patch_all()必须放到被打补丁者的前面,如time,socket模块之前
或者我们干脆记忆成:要用gevent,需要将from gevent import monkey;monkey.patch_all()放到文件的开头
把monkey.pathch_all() 下面所有代码的涉及到io阻塞操作都打个标记,变成非阻塞操作,让gevent可以识别
这样就可以检测到io操作
from gevent import monkey;monkey.patch_all() import gevent import time def eat(name): print("%s:eat 1" %name) time.sleep(3) print("%s:eat 2" %name) def play(name): print("%s:play 1" % name) time.sleep(4) print("%s:play 2" % name) g1 = gevent.spawn(eat,"mike") g2 = gevent.spawn(play,"mike") start_time = time.time() g1.join() g2.join() end_time = time.time() print(end_time-start_time) ''' mike:eat 1 mike:play 1 mike:eat 2 mike:play 2 4.032230854034424 '''
join() 主线程等待任务运行完后才销毁
joinall() 等待多个任务 用列表存放任务
from gevent import monkey;monkey.patch_all() import gevent import time def eat(name): print("%s:eat 1" %name) time.sleep(3) print("%s:eat 2" %name) def play(name): print("%s:play 1" % name) time.sleep(4) print("%s:play 2" % name) g1 = gevent.spawn(eat,"mike") g2 = gevent.spawn(play,"mike") gevent.joinall([g1,g2])