greenlet
安装:
pip install greenlet
import time
from greenlet import greenlet
# A
def task():
for i in range(3):
print('A'+str(i))
g1.switch()
time.sleep(0.3)
# C
def task1():
for i in range(3):
print('c'+str(i))
g2.switch()
time.sleep(0.3)
# B
def task2():
for i in range(3):
print('b'+str(i))
g.switch()
time.sleep(0.2)
if __name__ == '__main__':
# 调用函数
g = greenlet(task)
g1 = greenlet(task1)
g2 = greenlet(task2)
# 切换
g.switch()
g1.switch()
g2.switch()
运行结果
gevent
简介
gevent比greenlet更加强大,每遇到一个IO口需要消耗时间等待时,将会跳到下一个协程先执行
安装:
pip install gevent
# encoding:utf-8
import gevent
def show_wait(name, t):
for i in range(t):
print(name, '等待了', i+1,'s')
gevent.sleep(1) # 不需要等待就顺序执行,需要等待就自动切换
g1 = gevent.spawn(show_wait,'猪猪', 10 ) # 传入函数名,参数
g2 = gevent.spawn(show_wait,'呆呆', 10)
g3 = gevent.spawn(show_wait,'汪汪', 10 )
g1.join()
g2.join()
g3.join()
运行结果
gevent.monkey的使用
# encoding:utf-8
import gevent
import gevent.monkey
import urllib.request
'''gevent实现了自动化切换'''
gevent.monkey.patch_all() # 自动切换 在耗时操作中需要使用
def download(url):
print('start', url)
data = urllib.request.urlopen(url).read()
print('end', len(data))
gevent.joinall(
[
gevent.spawn(download, 'http://www.baidu.com/'),
gevent.spawn(download, 'http://www.163.com/'),
gevent.spawn(download, 'http://www.qq.com/')
]
)
运行结果