What is a coroutine?

前端 未结 10 1955
闹比i
闹比i 2020-11-28 17:27

What is a coroutine? How are they related to concurrency?

10条回答
  •  再見小時候
    2020-11-28 18:13

    From Programming in Lua, "Coroutines" section:

    A coroutine is similar to a thread (in the sense of multithreading): it is a line of execution, with its own stack, its own local variables, and its own instruction pointer; but it shares global variables and mostly anything else with other coroutines. The main difference between threads and coroutines is that, conceptually (or literally, in a multiprocessor machine), a program with threads runs several threads in parallel. Coroutines, on the other hand, are collaborative: at any given time, a program with coroutines is running only one of its coroutines, and this running coroutine suspends its execution only when it explicitly requests to be suspended.

    So the point is: Coroutines are "collaborative". Even in multi-core system, there is only one coroutine running at any given time (but multiple threads can run in parallel). There is non-preemptive between coroutines, the running coroutine must relinquish the execution explicitly.

    For "concurrency", you can refer Rob Pike's slide:

    Concurrency is the composition of independently executing computations.

    So during coroutine A's execution, it passes control to coroutine B. Then after some time, the coroutine B passes control back to coroutine A. Since there is dependency between coroutines, and they must run in tandem, so the two coroutines are not concurrency.

提交回复
热议问题