什么是Coroutine?

Coroutine,又称作协程。从字面上来理解,即协同运行的例程,它是比是线程(thread)更细量级的用户态线程,特点是允许用户的主动调用和主动退出,挂起当前的例程然后返回值或去执行其他任务,接着返回原来停下的点继续执行。等下,这是否有点奇怪?我们都知道一般函数都是线性执行的,不可能说执行到一半返回,等会儿又跑到原来的地方继续执行。但一些熟悉python(or其他动态语言)的童鞋都知道这可以做到,答案是用yield语句。其实这里我们要感谢操作系统(OS)为我们做的工作,因为它具有getcontext和swapcontext这些特性,通过系统调用,我们可以把上下文和状态保存起来,切换到其他的上下文,这些特性为coroutine的实现提供了底层的基础。

 

 

 

在Python的概念中,这里提到的协程就是生成器。

 

yield 与 return

在一个生成器中,如果没有return,则默认执行到函数完毕时返回StopIteration;

>>>defg1():
...yield1
...
>>>g=g1()
>>>next(g)#第一次调用next(g)时,会在执行完yield语句后挂起,所以此时程序并没有执行结束。
1
>>>next(g)#程序试图从yield语句的下一条语句开始执行,发现已经到了结尾,所以抛出StopIteration异常。
Traceback(most recent call last):
File"<stdin>",line1,in<module>
StopIteration
>>>

如果遇到return,如果在执行过程中 return,则直接抛出 StopIteration 终止迭代。

>>>defg2():
...yield'a'
...  return
...yield'b'
...
>>>g=g2()
>>>next(g)#程序停留在执行完yield 'a'语句后的位置。
'a'
>>>next(g)#程序发现下一条语句是return,所以抛出StopIteration异常,这样yield 'b'语句永远也不会执行。
Traceback(most recent call last):
File"<stdin>",line1,in<module>
StopIteration

 

如果在return后返回一个值,那么这个值为StopIteration异常的说明,不是程序的返回值。

生成器没有办法使用return来返回值。

>>>defg3():
...yield'hello'
...return'world'
...
>>>g=g3()
>>>next(g)
'hello'
>>>next(g)
Traceback(most recent call last):
File"<stdin>",line1,in<module>
StopIteration:world
 
 send()

生成器函数最大的特点是可以接受外部传入的一个变量,并根据变量内容计算结果后返回。
这是生成器函数最难理解的地方,也是最重要的地方,实现后面我会讲到的协程就全靠它了。

defgen():
value=0
whileTrue:
receive=yieldvalue
ifreceive=='e':
break
value='got: %s'%receive
 
g=gen()
print(g.send(None))    
print(g.send('aaa'))
print(g.send(3))
print(g.send('e'))

执行流程:

  1. 通过g.send(None)或者next(g)可以启动生成器函数,并执行到第一个yield语句结束的位置。此时,执行完了yield语句,但是没有给receive赋值。yield value会输出初始值0注意:在启动生成器函数时只能send(None),如果试图输入其它的值都会得到错误提示信息。
  2. 通过g.send(‘aaa’),会传入aaa,并赋值给receive,然后计算出value的值,并回到while头部,执行yield value语句有停止。此时yield value会输出”got: aaa”,然后挂起。
  3. 通过g.send(3),会重复第2步,最后输出结果为”got: 3″
  4. 当我们g.send(‘e’)时,程序会执行break然后推出循环,最后整个函数执行完毕,所以会得到StopIteration异常。

最后的执行结果如下:

 

0
got:aaa
got:3
Traceback(most recent call last):
File"h.py",line14,in<module>
print(g.send('e'))
StopIteration

 

throw()

用来向生成器函数送入一个异常,可以结束系统定义的异常,或者自定义的异常。
throw()后直接跑出异常并结束程序,或者消耗掉一个yield,或者在没有下一个yield的时候直接进行到程序的结尾。

defgen():
whileTrue:
try:
yield'normal value'
yield'normal value 2'
print('here')
exceptValueError:
print('we got ValueError here')
exceptTypeError:
break
 
g=gen()
print(next(g))
print(g.throw(ValueError))
print(next(g))
print(g.throw(TypeError))
 

输出结果为:
normal value
we got ValueErrorhere
normal value
normal value2
Traceback(most recent call last):
File"h.py",line15,in<module>
print(g.throw(TypeError))
StopIteration


解释:

  1. print(next(g)):会输出normal value,并停留在yield ‘normal value 2’之前。
  2. 由于执行了g.throw(ValueError),所以会跳过所有后续的try语句,也就是说yield ‘normal value 2’不会被执行,然后进入到except语句,打印出we got ValueError here。然后再次进入到while语句部分,消耗一个yield,所以会输出normal value。
  3. print(next(g)),会执行yield ‘normal value 2’语句,并停留在执行完该语句后的位置。
  4. g.throw(TypeError):会跳出try语句,从而print(‘here’)不会被执行,然后执行break语句,跳出while循环,然后到达程序结尾,所以跑出StopIteration异常。

 

下面给出一个综合例子,用来把一个多维列表展开,或者说扁平化多维列表) 

defflatten(nested):
 
try:
#如果是字符串,那么手动抛出TypeError。
ifisinstance(nested,str):
raiseTypeError
forsublist innested:
#yield flatten(sublist)
forelement inflatten(sublist):
#yield element
print('got:',element)
exceptTypeError:
#print('here')
yieldnested
 
L=['aaadf',[1,2,3],2,4,[5,[6,[8,[9]],'ddf'],7]]
fornum inflatten(L):
print(num)

如果理解起来有点困难,那么把print语句的注释打开在进行查看就比较明了了。

 

总结

  1. 按照鸭子模型理论,生成器就是一种迭代器,可以使用for进行迭代。
  2. 第一次执行next(generator)时,会执行完yield语句后程序进行挂起,所有的参数和状态会进行保存。再一次执行next(generator)时,会从挂起的状态开始往后执行。在遇到程序的结尾或者遇到StopIteration时,循环结束。
  3. 可以通过generator.send(arg)来传入参数,这是协程模型。
  4. 可以通过generator.throw(exception)来传入一个异常。throw语句会消耗掉一个yield。可以通过generator.close()来手动关闭生成器。
  5. next()等价于send(None)