亲宝软件园·资讯

展开

python gevent库

IT之一小佬 人气:0

前言:

安装gevent库:

pip install gevent

示例代码1:

from gevent import monkey  # 为了能识别time模块的io
 monkey.patch_all()  # 必须放到被打补丁者的前面,如 time,socket 模块之前
import gevent
import time
 def gf(name):
    print(f'{name}:我想打王者!!')
    # gevent.sleep(2)
    time.sleep(2)
    print(f'{name}:我想吃大餐!!!')
 def bf(name):
    print(f'{name}:一起打!!!')
    # gevent.sleep(2)
    time.sleep(2)
    print(f'{name}:一快去吃!!')
if __name__ == "__main__":
    start = time.time()
    # 创建协程对象
    g1 = gevent.spawn(gf, '张三')
    g2 = gevent.spawn(bf, '李四')
    # 开启任务
    g1.join()
    g2.join()
    end = time.time()
    print(end - start)

运行结果:

 示例代码2:

import gevent
 def foo():
    print('Running in foo')
    gevent.sleep(2)
    print('Explicit context switch to foo again')
 
def bar():
    print('Explicit context to bar')
    gevent.sleep(2)
    print('Implicit context switch back to bar')
 gevent.joinall([
    gevent.spawn(foo),
    gevent.spawn(bar),
])

运行结果:

加载全部内容

相关教程
猜你喜欢
用户评论