코 로 틴

지난번 에 concurrent http://bookjovi.iteye.com/blog/1333431 에 대해 서 얘 기 했 는데 Erlang 과 Go 언어 가 나 왔 습 니 다. 오늘 은 coroutine 에 대해 서 얘 기 하 겠 습 니 다. Erlang 에서 process 는 coroutine 이 라 고 할 수 없습니다. 마찬가지 로 Go 에서 도 coroutine 의 용 어 를 피하 고 goroutine 으로 바 뀌 었 습 니 다. 그러면 coroutine 은 무엇 입 니까?
 
coroutine 은 위 키 백과 에서 매우 상세 한 설명 을 가지 고 있 습 니 다. http://en.wikipedia.org/wiki/Coroutine
coroutine 과 Erlang process / goroutine 의 가장 큰 차 이 는 coroutine 이 한 스 레 드 에서 만 실 행 될 수 있 기 때문에 진정한 concurrent 라 고 할 수 없다. coroutine 에서 비교적 보편적 인 키 워드 는 yield 이 고 coroutine 에서 주동 적 으로 집행 권 을 포기 할 수 있 을 뿐 수 동적 으로 선점 할 수 없다.
coroutine 을 실현 하 는 언어 는 lua, Perl 6 (built - in), tcl (built - in) 등 이 있 습 니 다.
 
자바 에 coroutine 이 있 나 요?정 답 은 언어 차원 에 서 는 없 지만 다른 방식 으로 JVM http://openjdk.java.net/projects/mlvm/ 을 수정 할 수 있 습 니 다. jdk 8 에 이 방면 의 특성 을 더 할 수 있 기 를 바 랍 니 다 (자바 concurrent 특성 을 바 라 는 것 은 scala 언어 를 볼 수 있 기 를 바 랍 니 다).bluedavy 는 자바 에 관 한 coroutine 글 을 한 번 썼 습 니 다. 잘 썼 습 니 다.  http://blog.bluedavy.com/?p=4
 
사실 가끔 은 coroutine 이 몇 줄 의 C 코드 로 시 뮬 레이 션 을 할 수 있 습 니 다. "Coroutine in C" 를 보 세 요.
http://www.chiark.greenend.org.uk/~sgtatham/coroutines.html
int function(void) {
    static int i, state = 0;
    switch (state) {
        case 0: goto LABEL0;
        case 1: goto LABEL1;
    }
    LABEL0: /* start of function */
    for (i = 0; i < 10; i++) {
        state = 1; /* so we will come back to LABEL1 */
        return i;
        LABEL1:; /* resume control straight after the return */
    }
}

 멋 있 지?stack 을 전환 하지 않 고 간단 한 coroutine 을 모 의 했 습 니 다.
 
특히 go 언어의 저자 중 한 명인 Russ Cox 는 이전에 C 의 coroutine 라 이브 러 리 libtask http://swtch.com/libtask/ 를 쓴 적 이 있 는데 어때요?go 언어 와 비슷 하 죠? 이런 측면 에서 볼 때 go 는 libtask 를 언어 측면 에 이식 한 것 입 니 다.
 
C 의 coroutine 라 이브 러 리 는 아직도 많다.
https://github.com/halayli/lthread
http://www.dekorte.com/projects/opensource/libCoroutine/
http://www.goron.de/~froese/coro/
http://code.google.com/p/libconcurrency/
http://software.schmorp.de/pkg/libcoro.html
 
 
coroutine 개념 과 비슷 한 것 은 generator: http://en.wikipedia.org/wiki/Generator_(computer_programming) 도 있다.
generator 는 python, c \ #, ruby 에서 모두 실현 되 어 간단 한 iterator 를 실현 합 니 다.
 
continuations 개념 과 coroutine 도 비슷 합 니 다. 모 노 에 있 는 continuations api 를 보 겠 습 니 다.
 
     public class Continuation {
          public Continuation ();
          public void Mark ();
          public int Store (int state);
          public void Restore (int state);
     }

     var c = new Continuation ();
     ...
 
     switch (c.Store (0)){
     case 0:
          // First invocation
     case 1:
          // Restored from the point ahead.
     }
     ...
     // Jump back to the switch statement.
     c.Restore (1);

이 예 는 위 에 있 는 coroutine in C 랑 비슷 하지 않 아 요?continuation 을 C 안의 setjmp 와 longjmp 로 깊이 이해 할 수 있 습 니 다.
 
 
엉망 으로 썼 다!:)

좋은 웹페이지 즐겨찾기