生成器-send方法

python多任务-协程
同步 异步

同步-是指代码调用IO操作时 必须等待IO操作完成才返回调用方式 同步是串行
异步-是指代码调用IO操作时 不必等IO操作完成就返回的调用方式 异步是并行

阻塞 非阻塞
阻塞:从调用者的角度出发 如果在调用的时候被卡住 不能再继续向下运行 需要再等待 就说是阻塞
非阻塞:从调用都有角度出发 如果在调用的时候 凤有被卡住 能够继续向下运行 无需等待 不说是非阻塞
代码中 input-->等待输入是阻塞print -->是非阻塞
生成器-send方法
send方法有一个参数 该参数指定的是上一次被挂起的yield语句的返回值

使用yield完成多任务

'''
# 斐波拉契数列  0 1,1,2,3,5,8,13,21,
# 除了next 来启动生成器 还有其他什么方法可以? 可通知send方法
def create_num(num):
    a,b = 0,1
    current_num = 0

    while current_num < num:
        result = yield a
        print('result-->',result)
        a,b = b, a+b
        current_num += 1

 # return 'ellen'    # 如何获取返回值? 不可用for循环也不可用next 在异常捕获中取得

g = create_num(5)
# for i in p:
#     print(i)

print(next(g))
# print(next(g))
# print(next(g))
# print(next(g))
# print(next(g))

# while True:
#     try:
#         ret = next(g)
#         print(ret)
#     except Exception as e:
#         print(e)
#         # print(e.value,'--')
#         break

# 报错 不能发送非空值启动生成器 必须先发送一个None
# print(g.send('ellen'))

# print(g.send(None))
print(next(g))
# 关闭生成器
# g.close()
# 如果前面不调用next 第一次必须发送None
print(g.send('ellen'))
print(g.send('ellen'))
print(g.send('ellen'))
# # print(g.send('ellen'))
发布了35 篇原创文章 · 获赞 0 · 访问量 541

猜你喜欢

转载自blog.csdn.net/weixin_45905671/article/details/104045561