python gevnt实现协程

gevent

也是第三方库,自行调度协程,自动试别程序的耗时操作。比如读文件,等待时间。

代码举了个栗子

from gevent import monkey
monkey.patch_all()
import time
import gevent

def work1():
    while True:
        print("executing work1......" , gevent.getcurrent())
        time.sleep(0.5)

def work2():
    while True:
        print("executing work2......")
        time.sleep(0.5)

if __name__ == '__main__':

    #指派任务,gevent.spawn(函数名,参数1,参数2,......)
    g1 = gevent.spawn(work1)
    g2 = gevent.spawn(work2)

   #join是让主程序等待协程执行完再退出  
    g1.join()
    g2.join()

 

结果
executing work1...... <Greenlet at 0x31d1900: work1>
executing work2......
executing work1...... <Greenlet at 0x31d1900: work1>
executing work2......
executing work1...... <Greenlet at 0x31d1900: work1>
.......

 

特别说明

如果没有加下面两行代码,默认情况下就不能识别time.sleep(0.5)耗时操作, 这时可以用gevent.time(0.5)来代替

from gevent import monkey
monkey.patch_all()

 

打补丁

在不修改程序代码的情况下,为程序增加新的功能,

 

posted @ 2023-03-24 15:28  筱筱的春天  阅读(27)  评论(0编辑  收藏  举报