Friday, October 5, 2018

cooperative multitasking

過去初學 event-driven 或是 cooperative multitasking 時,沒有特別想清楚 。等到後來,多寫了一些 Nodejs 的 async/await ,還有 Clojure 的 go-block 之後,才覺得這個 cooperative multitasking 真的大有文章在。

這邊有一個參考資料,比較了兩種 cooperative multitasking 不同的實作方式:

實作一: 讓語言本身的排程器可以被 I/O 觸發,在 I/O blocking 的同時,自動做出 context-swtich 。這是 golang 的實作法。
實作二:讓 I/O 呼叫變成 non-blocking 的。這是 Nodejs, Python, Clojure 的實作法。

原文如下:
For cooperative concurrency to work well with I/O, the language should either make the scheduler aware of the I/O calls (to be able to switch to another context while blocking) or the I/O should be non-blocking. The former requires runtime support in the language, like Go; the latter is what programming environments like Python (with asyncio) and Node.js (with its fully non-blocking standard library) do. The same applies to Clojure, where core.async is just a library without actual runtime support.

在 golang ,如果要應用語言本身提供的同步特性,常見的寫法是:
將有 I/O 呼叫的函數,放在一個被 go 關鍵字修飾的函數裡頭 (即放在一個獨立的 goroutine 裡),並且透過 channel ,將 I/O 呼叫的結果送出來。