Coroutine 簡介
Coroutine 是一個可以被暫停和繼續跑的東西。
Coroutine 其實不是一個新的被提出的概念,他被提出的時間甚至早於 1990 年: MELVIN E. Conway 在做 COBOL Compiler 時就有用到它。
Under these conditions each module may be made into a coroutine; that is, it may be coded as an autonomous pro-gram which communicates with adjacent modules as if they were input or output subroutines. Thus, coroutines are subroutines all at the same level, each acting as if it were the master program when in fact there is no master program. There is no bound placed by this definition on the number of inputs and outputs a coroutine may have. The coroutine notion can greatly simplify the conception of a program when its modules do not communicate with each other synchronously. -- Design of a separable transition-diagram compiler
Coroutine 可以進行非阻塞式的通訊和資源分享,這使得它們在處理高併發任務、IO密集型操作、事件驅動程式設計以及異步編程等場景中特別有用。
與傳統的回調函數和多執行緒相比, Coroutine 具有更易於理解和維護的程式碼結構,同時能夠有效地減少 Deadlock 和併發競爭等問題。