您现在的位置是:课程教程文章

Python中Gevent的使用

2023-12-13 22:47课程教程文章 人已围观

1、可以通过gevent轻松实现并发同步或异步编程。gevent中使用的主要模式是Greenlet,它是以C扩展模块的形式访问Python的轻量级协程。

2、Greenlet全部运行在主程序操作系统的过程中,但是它们是协作调度的。

实例

fromgeventimportmonkey;#为了能识别time模块的io
monkey.patch_all()#必须放到被打补丁者的前面,如time,socket模块之前
importgevent
#pipinstallgevent
fromtimeimporttime,sleep

defgf(name):
print(f'{name}:我想打王者!!')
#gevent.sleep(2)
sleep(2)
print(f'{name}:我想吃大餐!!!')

defbf(name):
print(f'{name}:一起打!!!')
#gevent.sleep(2)
sleep(2)
print(f'{name}:一快去吃!!')

if__name__=="__main__":
start=time()
#创建协程对象
g1=gevent.spawn(gf,'貂蝉')
g2=gevent.spawn(bf,'吕布')

#开启任务
g1.join()
g2.join()
end=time()
print(end-start)

以上就是Python中Gevent的使用,希望对大家有所帮助。更多Python学习指路:python基础教程

课程教程:Python中Gevent的使用

上一篇:Python中选择结构是什么

下一篇:没有了

站点信息

  • 文章统计篇文章