博客
关于我
Python---协程(一)
阅读量:268 次
发布时间:2019-03-01

本文共 2798 字,大约阅读时间需要 9 分钟。

协程

  • 历史历程

    • 3.4引入协程,用yield实现
    • 3.5引入协程语法
    • 实现的协程比较好的包有asyncio, tornado, gevent
  • 定义:协程 是为非抢占式多任务产生子程序的计算机程序组件,协程允许不同入口点在不同位置暂停或开始执行程序”。

  • 从技术角度讲,协程就是一个你可以暂停执行的函数,或者干脆把协程理解成生成器

  • 协程的实现:

    • yield返回
    • send调用
  • 协程的四个状态

    • inspect.getgeneratorstate(…) 函数确定,该函数会返回下述字符串中的一个:
    • GEN_CREATED:等待开始执行
    • GEN_RUNNING:解释器正在执行
    • GEN_SUSPENED:在yield表达式处暂停
    • GEN_CLOSED:执行结束
    • next预激(prime)
    • 代码案例v2
  • 协程终止

    • 协程中未处理的异常会向上冒泡(传递到主线程),传给 next 函数或 send 方法的调用方(即触发协程的对象)
    • 终止协程的一种方式:发送某个哨符值,让协程退出。内置的 None 和Ellipsis 等常量经常用作哨符值。
  • yield from

    • 调用协程为了得到返回值,协程必须正常终止
    • 生成器正常终止会发出StopIteration异常,异常对象的vlaue属性保存返回值
    • yield from从内部捕获StopIteration异常
    • 案例v03
    • 委派生成器
      • 包含yield from表达式的生成器函数
      • 委派生成器在yield from表达式出暂停,调用方可以直接把数据发给子生成器
      • 子生成器在把产出的值发给调用放
      • 子生成器在最后,解释器会抛出StopIteration,并且把返回值附加到异常对象上
      • 案例v04
# 协程代码案例1def simple_coroutine():    print('-> start')    x = yield    print('-> recived', x)    yield#主线程sc = simple_coroutine()print(1111)# 可以使用sc.send(None),效果一样next(sc) #预激print(2222)sc.send('zhexiao')
# 案例v2,  协程的状态def simple_coroutine(a):    print('-> start')    b = yield a    print('-> recived', a, b)    c = yield a + b    print('-> recived', a, b, c)# runcsc = simple_coroutine(5)aa = next(sc)print(aa)bb = sc.send(6) # 5, 6print(bb)cc = sc.send(7) # 5, 6, 7print(cc)
# 案例v03def gen():    for c in 'AB':        yield c# list直接用生成器作为参数print(list(gen()))def gen_new():    yield from 'AB'print(list(gen_new()))
# 案例v04, 委派生成器from collections import namedtuple'''解释:1. 外层 for 循环每次迭代会新建一个 grouper 实例,赋值给 coroutine 变量; grouper 是委派生成器。2. 调用 next(coroutine),预激委派生成器 grouper,此时进入 while True 循环,调用子生成器 averager 后,在 yield from 表达式处暂停。3. 内层 for 循环调用 coroutine.send(value),直接把值传给子生成器 averager。同时,当前的 grouper 实例(coroutine)在 yield from 表达式处暂停。4. 内层循环结束后, grouper 实例依旧在 yield from 表达式处暂停,因此, grouper函数定义体中为 results[key] 赋值的语句还没有执行。5. coroutine.send(None) 终止 averager 子生成器,子生成器抛出 StopIteration 异常并将返回的数据包含在异常对象的value中,yield from 可以直接抓取 StopItration 异常并将异常对象的 value 赋值给 results[key]'''ResClass = namedtuple('Res', 'count average')# 子生成器def averager():    total = 0.0    count = 0    average = None    while True:        term = yield        # None是哨兵值        if term is None:            break        total += term        count += 1        average = total / count    return ResClass(count, average)# 委派生成器def grouper(storages, key):    while True:        # 获取averager()返回的值        storages[key] = yield from averager()# 客户端代码def client():    process_data = {           'boys_2': [39.0, 40.8, 43.2, 40.8, 43.1, 38.6, 41.4, 40.6, 36.3],        'boys_1': [1.38, 1.5, 1.32, 1.25, 1.37, 1.48, 1.25, 1.49, 1.46]    }    storages = {   }    for k, v in process_data.items():        # 获得协程        coroutine = grouper(storages, k)        # 预激协程        next(coroutine)        # 发送数据到协程        for dt in v:            coroutine.send(dt)        # 终止协程        coroutine.send(None)    print(storages)# runclient()

转载地址:http://srba.baihongyu.com/

你可能感兴趣的文章
nginx 后端获取真实ip
查看>>
Nginx 多端口配置和访问异常问题的排查与优化
查看>>
Nginx 如何代理转发传递真实 ip 地址?
查看>>
Nginx 学习总结(16)—— 动静分离、压缩、缓存、黑白名单、性能等内容温习
查看>>
Nginx 学习总结(17)—— 8 个免费开源 Nginx 管理系统,轻松管理 Nginx 站点配置
查看>>
Nginx 学习(一):Nginx 下载和启动
查看>>
nginx 常用指令配置总结
查看>>
Nginx 常用配置清单
查看>>
nginx 常用配置记录
查看>>
nginx 开启ssl模块 [emerg] the “ssl“ parameter requires ngx_http_ssl_module in /usr/local/nginx
查看>>
Nginx 我们必须知道的那些事
查看>>
Nginx 源码完全注释(11)ngx_spinlock
查看>>
Nginx 的 proxy_pass 使用简介
查看>>
Nginx 的配置文件中的 keepalive 介绍
查看>>
Nginx 结合 consul 实现动态负载均衡
查看>>
Nginx 负载均衡与权重配置解析
查看>>
Nginx 负载均衡详解
查看>>
nginx 配置 单页面应用的解决方案
查看>>
nginx 配置https(一)—— 自签名证书
查看>>
nginx 配置~~~本身就是一个静态资源的服务器
查看>>