• 协程


    一、协程的理解

    子程序/子函数:在所有语言中,都是层级调用。比如:A调用B,在B执行
    的过程中又可以调用C,C执行完毕返回,B执行完毕返回,最后是A执行完毕
    它是通过栈实现的,一个线程就是一个子程序,子程序调用总是一个入口,一次返回,调用的顺序是明确的

    概述:协程看上去也是子程序,但执行过程中,在子程序的内部可中断。
    然后转而执行别的子程序,不是函数调用,有点类似CPU中断。

    举个例子:
    def C():
    print("C--start")
    print('C--end')

    def B():
    print('B--start')
    C()
    print('B--end')


    def A():
    print('A--start')
    B()
    print('A--end')

    A()

    def A():

    print(1)
    print(2)
    print(3)

    def B():

    print('x')
    print('y')
    print('z')

    1
    2
    x
    y
    z
    3

    执行出这个结构
    但是A中没有B的调用
    看起来A、B执行过程有点像线程,但协程的特点在于是一个线程执行

    与线程相比,协程的执行效率极高,为什么极高?
    因为它只有一个线程,也不存在同时写变量的冲突,在协程中共享资源不加锁,只需要判断状态

    二、协程原理

    Python对协程的支持是通过generator实现的
     1 def run():
     2     print(1)
     3     yield 10
     4     print(2)
     5     yield 20
     6     print(3)
     7     yield 30
     8 
     9 
    10 # 协程的最简单风格,控制函数的阶段执行,节约线程或者进程的切换
    11 m = run()  #返回值是一个生成器 代码不会往下执行!!!
    12 print(next(m))
    13 print(next(m))
    14 print(next(m))
    协程原理

    三、数据传输

     1 def run():
     2     print(1)
     3     yield 10
     4     print(2)
     5     yield 20
     6     print(3)
     7     yield 30
     8 
     9 
    10 # 协程的最简单风格,控制函数的阶段执行,节约线程或者进程的切换
    11 m = run()  #返回值是一个生成器 代码不会往下执行!!!
    12 print(next(m))
    13 print(next(m))
    14 print(next(m))
    数据传输

    四、生产者与消费者

     1 def product(c):
     2     c.send(None)
     3     for i in range(5):
     4         print('生产者产生数据%d' % i)
     5         r = c.send(str(i))
     6         print('消费者消费了数据%s' % r)
     7     c.close()
     8     
     9     
    10 def customer():
    11     data = ''
    12     while True:
    13         n = yield data
    14         if not n:
    15             return
    16         print('消费者消费了%s' % n)
    17         data = 200
    18         
    19         
    20 c = customer()
    21 product(c)
    生产者与消费者
  • 相关阅读:
    flume sink两种类型 file_rool 自定义sing com.mycomm.MySink even if there is only one event, the event has to be sent in an array
    为什么引入进程20年后,又引入线程?
    As of Flume 1.4.0, Avro is the default RPC protocol.
    Google Protocol Buffer 的使用和原理
    Log4j 2
    统一日志 统一订单
    网站行为跟踪 Website Activity Tracking Log Aggregation 日志聚合 In comparison to log-centric systems like Scribe or Flume
    Percolator
    友盟吴磊:移动大数据平台的架构、实践与数据增值
    Twitter的RPC框架Finagle简介
  • 原文地址:https://www.cnblogs.com/linpd/p/10056238.html
Copyright © 2020-2023  润新知