风-fmgao

导航

gevent异步,io自动切换

#!/usr/bin/env python
# encoding: utf-8  
# Date: 2018/6/19

# # from gevent import monkey  # 这俩行必须放在首行,下面就可以使用time(非gevent)的io
# # monkey.patch_all()  # 相当于把所有的io操作打了标记,把io阻塞操作变成了非阻塞操作
# # gevent遇到io都可以自动切换
# import gevent
# import time
#
#
# def eat(name):
#     print('%s eat 1' % name)
#     gevent.sleep(3)  # 相当于io操作
#     # time.sleep(3)  # gevent不识别,只是别自己的io
#     print('%s eat 2' % name)
#
#
# def play(name):
#     print('%s play 1' % name)
#     gevent.sleep(4)
#     print('%s play 2' % name)
#
#
# start_time = time.time()
# g1 = gevent.spawn(eat, 'egon')  # 提交任务是异步提交
# g2 = gevent.spawn(play, 'alex')
#
# g1.join()
# g2.join()
# stop_time = time.time()
# print(stop_time - start_time)  # 4.005170583724976

# gevent 异步提交任务
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, 'egon')  # 提交任务是异步提交
g2 = gevent.spawn(play, 'alex')

# time.sleep(5)  # 保证线程在5秒内可以执行完
# g1.join()  # 同上一行代码,不用考虑时间
# g2.join()

# 终极
gevent.joinall([g1, g2])

posted on 2018-06-19 21:27  风-fmgao  阅读(197)  评论(0编辑  收藏  举报