Go Concurrency and Parallelism
January 22, 2025 · 1 min read · Page View:
If you have any questions, feel free to comment below.
Process and Thread #
The process is the program execution process in the operating system, and it is an independent unit for resource allocation and scheduling.
The thread is the execution entity of the process, the basic unit for CPU scheduling and distribution, and it is a smaller unit that can run independently.
A process can create and cancel multiple threads; multiple threads in the same process can execute concurrently.
Concurrency and Parallelism #
Concurrency is multiple threads running on the same CPU core.
Parallelism is multiple threads running on multiple CPU cores.
Goroutine #
A thread can run multiple goroutines, and a goroutine is a lightweight thread, which is managed by the Go runtime, independent stack space, shared heap space, scheduling controlled by the user, essentially similar to user-level threads. The cost of routine is KB level which is much lower than thread MB level.
goroutine is just a super “thread pool” implemented by the official. The 4~5KB stack memory occupied by each instance and the greatly reduced creation and destruction overhead due to the implementation mechanism are the fundamental reason for Go’s high concurrency.
A goroutine must correspond to a function, you just need to add the go
keyword before the function.
func hello() {
fmt.Println("Hello Goroutine!")
}
func main() {
go hello() // use goroutine
fmt.Println("main goroutine done!")
}
// output:
// main goroutine done!
// why? the main goroutine life cycle is over, the program will exit.
// this only for the main goroutine, so for the other goroutine, if return, the sub-routine can still running.
Use sync.WaitGroup
to wait all goroutine done.
var wg sync.WaitGroup
func hello(i int) {
defer wg.Done() // goroutine done, add -1
fmt.Println("Hello Goroutine!", i)
}
func main() {
for i := 0; i < 10; i++ {
wg.Add(1) // add a goroutine
go hello(i)
}
wg.Wait() // wait all goroutine done
}
Related readings
If you find this blog useful and want to support my blog, need my skill for something, or have a coffee chat with me, feel free to: