#使用生成器完成斐波那锲 def create_num(all_num): a, b = 0, 1 current_num = 0 while current_num < all_num: yield a#有yield就是生成器 a, b = b, a+b current_num += 1 obj = create_num(10) for i in obj: print(i)
#使用生成器完成斐波那锲 def create_num(all_num): a, b = 0, 1 current_num = 0 while current_num < all_num: yield a#有yield就是生成器 #遇到yield会暂停,再次调用函数的时候回从yield的地方开始执行 a, b = b, a+b current_num += 1 obj = create_num(10) #生成器是一种特殊的迭代器 ret = next(obj) print(ret) ret = next(obj) print(ret) for i in obj: print(i)
使用生成器实现多任务
#使用yield完成多任务 import time def task_1(): while True: print("----1----") time.sleep(0.1) yield def task_2(): while True: print("----2----") time.sleep(0.1) yield def main(): #创建生成器对象 t1 = task_1() t2 = task_2() while True: next(t1) next(t2)#实现了函数的交替执行,交替的实现函数的多任务 if __name__=="__main__": main()
用gevent代替next
import gevent import time def f1(n): for i in range(n): print(gevent.getcurrent(),i) # time.sleep(0.1) gevent.sleep(0.1)#gevent遇到延时就会多任务,延时操作不能用上面的那种方式,必须要用这样的 def f2(n): for i in range(n): print(gevent.getcurrent(),i) # time.sleep(0.2) gevent.sleep(0.1) print("-----1-----") g1 = gevent.spawn(f1,5) print("-----2-----") g2 = gevent.spawn(f2,5) g1.join() g2.join()
import gevent import time
from gevent import monkey monkey.patch_all()#加上这个语句的话就不需要再使用gevent.sleep(0.1)这样的延时语句了,time.sleep(0.1)也可以用了 def f1(n): for i in range(n): print(gevent.getcurrent(),i) time.sleep(0.1) def f2(n): for i in range(n): print(gevent.getcurrent(),i) time.sleep(0.1) print("-----1-----") g1 = gevent.spawn(f1,5) print("-----2-----") g2 = gevent.spawn(f2,5) g1.join() g2.join()
import gevent import time from gevent import monkey monkey.patch_all()#加上这个语句的话就不需要再使用gevent.sleep(0.1)这样的延时语句了,time.sleep(0.1)也可以用了 def f1(n): for i in range(n): print(gevent.getcurrent(),i) time.sleep(0.1) def f2(n): for i in range(n): print(gevent.getcurrent(),i) time.sleep(0.1) gevent.joinall([gevent.spawn(f1,5),gevent.spawn(f2,5)])