gevent方法实现多任务(协程)
from gevent import monkey
import gevent
import random
import time
# 有耗时操作时需要
# 将程序中用到的耗时操作的代码,换为gevent中自己实现的模块
monkey.patch_all()
def coroutine_work(coroutine_name):
for i in range(10):
print(coroutine_name, i)
time.sleep(random.random())
#写了monkey.patch_all()就可以用time.sleep,不写就需要gevent.sleep
# gevent.sleep(1)
#执行创建的协程
gevent.joinall([
gevent.spawn(coroutine_work, "work1"),
gevent.spawn(coroutine_work, "work2")
])
了解yield和grenlet
yield方法创建协程
from time import sleep
def task1():
while True:
print('---1---')
sleep(1)
yield
def task2():
while True:
print('---2---')
sleep(1)
yield
def main():
t1 = task1()
t2 = task2()
#循环拿到task1和task2的值
while True:
next(t1)
next(t2)
if __name__ == "__main__":
main()
greenlet方法创建协程
from greenlet import greenlet
import time
def test1():
while True:
print("---A---")
#切换执行gr2
gr2.switch()
time.sleep(0.5)
def test2():
while True:
print("---B---")
#切换执行gr1
gr1.switch(0.5)
gr1 = greenlet(test1)
gr2 = greenlet(test2)
#先执行gr1
gr1.switch()
网友评论