Home >Backend Development >Golang >What is the difference between coroutines and threads in golang?
The difference between coroutines and threads in golang
Generally speaking, coroutines are like lightweight threads.
Threads generally have a fixed stack and a fixed size. In order to avoid resource waste (or lack of resources), goroutines adopt a dynamic expansion and contraction strategy: the initial amount is 2k, and the maximum can be expanded to 1G.
Each thread has an id, which will be returned when the thread is created, so we can manipulate the thread through the thread's id. But there is no such concept in golang, so we must consider the creation and release of coroutines at the beginning of coding.
In terms of scheduling overhead for thread and goroutine switching
In terms of thread/goroutine switching overhead, goroutine is far smaller than threads
Thread: involves mode switching (switching from user mode to kernel mode ), 16 registers, PC, SP... and other register refreshes, etc.
Because the coroutine is completed by the coroutine scheduler in user mode and does not need to be trapped in the kernel, the cost is small.
So goroutine: Only the values of three registers are modified - PC/SP/DX.
Related recommendations: golang tutorial
The above is the detailed content of What is the difference between coroutines and threads in golang?. For more information, please follow other related articles on the PHP Chinese website!