feishicheng 2020-05-31
""" 协程,运行的时候轮流去执行各个任务,如果生产者生产的速度比较慢,这里可以使用者个切换出去 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")