协程
- 使用yield
import time
def work1():
while True:
print("in work1")
yield
time.sleep(1)
def work2():
while True:
print("in work2")
yield
time.sleep(1)
def main():
# 生成器对象
w1 = work1()
w2 = work2()
while True:
next(w1)
next(w2)
if __name__ == '__main__':
main()
结果:
图解:
- 使用greenlet(需手动切换)
import greenlet
import time
def work1():
while True:
print("in work1")
# 切换到gr2进程
gr2.switch()
time.sleep(1)
def work2():
while True:
print("in work2")
# 切换到gr1进程
gr1.switch()
time.sleep(1)
gr1 = greenlet.greenlet(work1)
gr2 = greenlet.greenlet(work2)
gr1.switch()
结果:(无限循环)
- 使用gevent
import gevent
import time
from gevent import monkey
# 将默认阻塞变为非阻塞
monkey.patch_all()
def func():
for i in range(3):
print("当前协程 %s 正在运行" % gevent.getcurrent())
time.sleep(1)
def main():
# 创建协程
g1 = gevent.spawn(func)
g2 = gevent.spawn(func)
g3 = gevent.spawn(func)
# join 阻塞等待协程完成并结束
# g1.join()
# g2.join()
# g3.join()
gevent.joinall([g1,g2,g3])
if __name__ == '__main__':
main()
结果:(协程的执行是无序的)