協程

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

發佈了32 篇原創文章 · 獲贊 13 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章