1.coroutine
Translation:
routine例程
coroutine协程
subroutine子例程
Concept:
allowing multiple entry points for suspending and resuming execution at certain locations
Naming from:
coroutine (cooperative routine), for implementing cooperative tasks
Coroutine
http://en.wikipedia.org/wiki/Coroutine
Revisiting Coroutines
http://www.inf.puc-rio.br/~roberto/docs/MCC15-04.pdf
协程
http://zh.wikipedia.org/wiki/%E5%8D%8F%E7%A8%8B
2.Comparison with subroutines
“Subroutines are special cases of … coroutines.” –Donald Knuth.
子例程只有一个入口点且只返回一次且返回到其调用者,而协程允许多个入口点且可以跳出多次且不一定返回到调用者
3.Implementation
Coroutines are best implemented using continuations.
4.协程与用户态线程的区别
协程的真正意义在于例程的调出调入。用于实现协作式的例程切换。这种例程可用于与异步机制配合解决阻塞调用问题。
协程只是负责用户态线程实现当中的线程切换的实现。
用户态线程不一定用到协程,任务队列+线程/线程池也是用户态线程,只是不能切换,比如scala的actor
另外,erlang的轻量机进程是虚拟机实现的
用户线程也不一定都是协作式调度策略,比如erlang的轮转调度策略,go 1.2后具有简单抢占机制的调度策略
5.coroutine的分类
对称( symmetric)协程
var q := new queue
coroutine produce
loop
while q is not full
create some new items
add the items to q
switch to consume
coroutine consume
loop
while q is not empty
remove some items from q
use the items
switch to produce
非对称协程( asymmetric coroutines)
var q := new queue
generator produce
loop
while q is not full
create some new items
add the items to q
yield consume
generator consume
loop
while q is not empty
remove some items from q
use the items
yield produce
subroutine dispatcher
var d := new dictionary(generator → iterator)
d[produce] := start produce
d[consume] := start consume
var current := produce
loop
current := next d[current]
6.common use
implementing more familiar program components such as cooperative tasks, exceptions, event loop, iterators, infinite lists and pipes.
State machines within a single subroutine
Actor model of concurrency
Generators
Communicating sequential processes
Producer / consumer patterns
Multiplexed I/O
7.Languages with native support
F# Ruby Pascal Go Scheme Haskell Perl C# PHP Javascript Tcl Python Stackless_python Lua Rubby Simula Cilkplus
Erlang
9. C/C++的coroutine
参看http://blog.csdn.net/cadem/article/details/48653553
10.Java coroutine
10.1. kilim
11.Lua的coroutine
Lua语言实现的协程是一种非对称式 (asymmetric)协程,或称半对称式(semi-symmetric)协程,又或干脆就叫半协程(semi-coroutine)。
12.Python的coroutine
Greenlet – python下著名的协程库
gevent – using greenlet 的并发模型/网络库
eventlet 基于greenlet的并发模型/网络库
Stackless python
Greenlet