Python协程一点理解


协程,又称微线程,纤程。英文名Coroutine。

线程是系统级别的它们由操作系统调度,而协程则是程序级别的由程序根据需要自己调度。在一个线程中会有很多函数,我们把这些函数称为子程序,在子程序执行过程中可以中断去执行别的子程序,而别的子程序也可以中断回来继续执行之前的子程序,这个过程就称为协程。也就是说在同一线程内一段代码在执行过程中会中断然后跳转执行别的代码,接着在之前中断的地方继续开始执行,类似与yield操作。

协程拥有自己的寄存器上下文和栈。协程调度切换时,将寄存器上下文和栈保存到其他地方,在切回来的时候,恢复先前保存的寄存器上下文和栈。因此:协程能保留上一次调用时的状态(即所有局部状态的一个特定组合),每次过程重入时,就相当于进入上一次调用的状态,换种说法:进入上一次离开时所处逻辑流的位置。

协程,英文名是 Coroutine, 又称为微线程,是一种用户态的轻量级线程。协程不像线程和进程那样,需要进行系统内核上的上下文切换,协程的上下文切换是由程序员决定的。在 Python 中协程就是一个可以暂停执行的函数,听起来和生成器的概念一样。

协程的优点:

  (1)无需线程上下文切换的开销,协程避免了无意义的调度,由此可以提高性能(但也因此,程序员必须自己承担调度的责任,同时,协程也失去了标准线程使用多CPU的能力)

  (2)无需原子操作锁定及同步的开销

  (3)方便切换控制流,简化编程模型

  (4)高并发+高扩展性+低成本:一个CPU支持上万的协程都不是问题。所以很适合用于高并发处理。

协程的缺点:

  (1)无法利用多核资源:协程的本质是个单线程,它不能同时将 单个CPU 的多个核用上,协程需要和进程配合才能运行在多CPU上.当然我们日常所编写的绝大部分应用都没有这个必要,除非是cpu密集型应用。

  (2)进行阻塞(Blocking)操作(如IO时)会阻塞掉整个程序

yield

def test():
    for i in 'abc':
        yield i
    for i in [1, 2, 3]:
        yield i


if __name__ == '__main__':
    gen = test()
    print(gen.send(None))
    print(gen.send(None))
    print(gen.send(None))
    print(gen.send(None))
    print(gen.send(None))
    print(gen.send(None))
    print(gen.send(None))
def test():
    for i in 'abc':
        yield i
    for i in [1, 2, 3]:
        yield i


if __name__ == '__main__':
    gen = test()
    for i in gen:
        print(i)

使用for循环生成器,因为for循环可以捕捉StopIteration异常。

yield from

上面的代码也可以用yield from实现

def test():
    yield from 'abc'
    yield from [1, 2, 3]


if __name__ == '__main__':
    gen = test()
    for i in test():
        print(i)

yield from 后面需要加的是可迭代对象,它可以是普通的可迭代对象,也可以是迭代器,甚至是生成器。

使用yield from实现实时计算器

def average_gen():
    """
    子生成器
    """
    average = 0
    total = 0
    count = 0
    while True:
        num = yield average
        if num is None:
            break
        count += 1
        total += num
        average = total / count
    return average, count, total


def proxy_gen():
    """
    委派生成器
    """
    while True:
        average, count, total = yield from average_gen()
        print(f'平均值{average}, 计算{count}次, 总和{total}')


def client():
    """
    调用端
    """
    calc_average = proxy_gen()
    calc_average.send(None)
    # next(calc_average)
    # 预激活协程
    print(calc_average.send(10))
    print(calc_average.send(20))
    print(calc_average.send(30))
    calc_average.send(None)
    # 关闭协程


if __name__ == '__main__':
    client()

在委派生成器中的while True可以替换成for循环,循环的大小决定调用端可以calc_average.send(None)的次数(第一次预激活也计入)。

while Truefor循环用来捕捉StopIteration异常,可以查看第一段代码。

示例

def average_gen():
    """
    子生成器
    """
    average = 0
    total = 0
    count = 0
    while True:
        num = yield average
        if num is None:
            break
        count += 1
        total += num
        average = total / count
    return average, count, total


def proxy_gen():
    """
    委派生成器
    """
    for i in range(2):
        average, count, total = yield from average_gen()
        print(f'平均值{average}, 计算{count}次, 总和{total}')


def client():
    """
    调用端
    """
    calc_average = proxy_gen()
    calc_average.send(None)
    # next(calc_average)
    # 预激活协程
    print(calc_average.send(10))
    print(calc_average.send(20))
    print(calc_average.send(30))
    calc_average.send(None)
    # 关闭协程
    print(calc_average.send(10))
    print(calc_average.send(20))
    print(calc_average.send(30))
    calc_average.send(None)


if __name__ == '__main__':
    client()

示例最后会抛出StopIteration异常。

因为在第二次calc_average.send(None)时,for循环捕捉了一次异常,进入了最后一次循环,在calc_average.send(None)时,for不能再次循环,不能处理StopIteration异常,故抛出。