python 协程
""" 协程,运行的时候轮流去执行各个任务,如果生产者生产的速度比较慢,这里可以使用者个切换出去 greenlet 会交出执行权,但是如果后面的耗时任务也不会就进入耗时,等下次轮到了,还是要进行耗时 这个程序的效果就只能够是轮询,起不到实际的节约时间的效果 """ import time from datetime import datetime from greenlet import greenlet def task1(): for i in range(5): print(datetime.now(), ": task1---" + str(i)) g2.switch() time.sleep(2) def task2(): for i in range(5): print(datetime.now(), ": task2---" + str(i)) g3.switch() time.sleep(2) def task3(): for i in range(5): print(datetime.now(), ": task3---" + str(i)) g1.switch() time.sleep(2) # 代表耗时任务 if __name__ == ‘__main__‘: g1 = greenlet(task1) g2 = greenlet(task2) g3 = greenlet(task3) g1.switch() print("over")
""" 协程,运行的时候轮流去执行各个任务,如果生产者生产的速度比较慢,这里可以使用者个切换出去 yield 会交出执行权,但是如果后面的耗时任务也不会就进入耗时,等下次轮到了,还是要进行耗时 这个程序的效果就只能够是轮询,起不到实际的节约时间的效果 """ import time from datetime import datetime def task1(): for i in range(5): print(datetime.now(), ": task1---" + str(i)) yield time.sleep(2) def task2(): for i in range(5): print(datetime.now(), ": task2---" + str(i)) yield time.sleep(2) def task3(): for i in range(5): print(datetime.now(), ": task3---" + str(i)) yield time.sleep(2) # 代表耗时任务 if __name__ == ‘__main__‘: g1 = task1() g2 = task2() g3 = task3() while True: try: next(g1) next(g2) next(g3) except: break print("over")
相关推荐
efeve 2020-09-14
ericxieforever 2020-09-03
Dimples 2020-06-08
鲁鲁酱 2020-06-02
paopao00 2020-05-10
georgeandgeorge 2020-05-09
Greatemperor 2020-05-03
jacktangj 2020-04-17
CloudXli 2020-04-07
oXiaoChong 2020-04-07
学习备忘录 2020-02-18
wyqwilliam 2020-02-10
PythonMaker 2020-01-19
ddxygq 2019-12-30
shengge0 2019-12-26
sschencn 2019-12-19
SDUTACM 2019-12-09
千锋 2019-12-07
Laozizuiku 2019-12-04
mayflowers 2019-11-18
wklken的笔记 2019-11-01