什麼是Goroutine?


什麼是Goroutine?

 











以這張圖為例,最上面的Go program就是我們寫的程式。

在 Go 語言中,每個 Go program都運行在一個稱為 Go runtime 的運行系統之上。

Go runtime是什麼?

In Go, the runtime is an essential part of the language that manages memory allocation, garbage collection, and scheduling of goroutines. The Go program interacts with the runtime through the Go standard library, which provides an abstraction layer over the runtime. The Go program is compiled into machine code and executed by the operating system. When the program starts, it initializes the Go runtime, which sets up the memory management system, creates the main goroutine, and starts the scheduler.

The Go program can create additional goroutines to run concurrently with the main goroutine. The runtime manages the scheduling of these goroutines, ensuring that they execute efficiently and safely. The runtime also handles the communication and synchronization between goroutines through channels and other synchronization primitives. Therefore, the Go program and the Go runtime are tightly integrated, with the runtime providing the underlying infrastructure that enables the program to execute efficiently and concurrently.

然後最底層是Operating system, 程式碼會被編譯成machine code在OS執行。

在Scheduler和OS之間就有一個稱為Thread的構造。無論使用哪種OS,Thread都是OS用來管理其併發性的工具。當OS跟蹤同時發生的多個事情時,它們使用Thread來區分這些工作。












Scheduler的工作是將這些 goroutine(也稱為虛擬線程,這些線程純粹由我們的 Go program維護)映射到OS的thread上。然而,goroutine 有限制,因為它不直接與OS互動,所以它本身無法做任何事情。這就是Scheduler發揮作用的地方。Scheduler會將 goroutine 映射到OS的thread上。


 








goroutine跟thread差異

通常thread有固定的stack space, 約1mb

而goroutine的stack space是變動的, 起始大小為2kb

thread被os管理,goroutine被 Go runtime管理

thread比較消耗資源, goroutine相較起來較少



ps. go runtime簡介













0 Comments:

張貼留言