cymetrics / blog

Cymetrics 技術部落格
https://tech-blog.cymetrics.io
MIT License
55 stars 5 forks source link

Java’s Thread Model and Golang Goroutine #7

Open utterances-bot opened 2 years ago

utterances-bot commented 2 years ago

Java’s Thread Model and Golang Goroutine

說到 Golang,總會提到其高併發的特性,而 goroutine 則是撐起 Golang 高併發的基礎。本文試著比較 Java thread 和 Golng goroutine 在 OS 運行的方式,讓大家能理解 goroutine 在設計上的獨到之處。 # Java...

https://tech-blog.cymetrics.io/posts/genchilu/javas-thread-model-and-golang-goroutine-zh/

techeternalriverco commented 2 years ago

Genchilu 大你好: 之前我在 facebook 有跟你討論過相關的問題是 Golang 用 GOMAXPROCS 這參數決定 gouroutine 使用多少 thread,預設是 core 數量。 但在 block system call 後的測試中,我們可以看到 thread 有 142 。 這樣個概念是否有衝突?

你當時的回覆是: GOMAXPROCS 決定 golang application 層最大的 thread 數量。 當呼叫 blocking system call 時 golang 會創建新的 thread 去接手 processor,讓 application 那一層始終維持一定數量的 thread 所以當你使用 goroutine call blocking system call 時,很容易會創建多的 thread,但大部分都是在執行 blocking system call,其他只有 GOMAXPROCS 個 thread 在 golang 的 application 服務

以下有幾個地方還不是特別清楚

  1. 所謂的 golang application 層是指 run time 的 golang 嗎?
  2. 當你使用 goroutine call blocking system call 時,很容易會創建多的 thread,但大部分都是在執行 blocking system call,其他只有 GOMAXPROCS 個 thread 在 golang 的 application 服務;這部分是否理解成 golang 還是會開多的 thread 但是在 handle scheduler 的數量還是以 GOMAXPROCS 的為主。

最近在看 OS 恐龍書,我是否可以理解 goroutine 是在開 user-level thread ,透過 scheduler 去跟 kernel-level thread 做多對多的關係?

以上問題,先感謝 Genchilu 大撥冗閱讀回覆。

aszx87410 commented 2 years ago

@genchilu

genchilu commented 2 years ago

@sonorous-lester

這邊指的是 golang 開放給開發者可以用 golang 程式控制的部分,為了方便溝通我簡稱為 golang application 層,實際上並沒有一個正式的名稱。

亦即是如果你是 golang 開發者,透過 go 這個語法開 goroutine,你寫的 golang code 最多就是只有 GOMAXPROCS thread 在處理。

但是當你寫的 code 需要執行 blocking system call 時 (例如讀檔),這時 application 能使用的 thread 數量就會減少,於是 golang 就會向 OS 溝通創建新的 thread,讓 application 曾始終維持 GOMAXPROCS 可以執行 goroutine。