Home  >  Article  >  Backend Development  >  Is golang a multi-threaded mode?

Is golang a multi-threaded mode?

coldplay.xixi
coldplay.xixiOriginal
2020-07-22 09:31:365782browse

Golang is a multi-threaded model. The thread model of golang is the MPG model. Generally speaking, Go processes and kernel threads correspond to many-to-many, so first of all, they must be multi-threaded.

Is golang a multi-threaded mode?

golang is a multi-threaded mode.

Since p and m in gmp bind p to the m kernel thread, then the maximum number of p is determined by GOPROCESS, and the number of M kernel threads will be limited to 10K by go. , but due to kernel reasons it cannot do so much, so this restriction can be treated as if it does not exist. Take a picture to clarify

Is golang a multi-threaded mode?

Golang has some so-called M ratio N model. N go routines can be created under M threads. Generally speaking, N is much larger than M. Essentially It is a multi-threaded model, but the scheduling of coroutines is determined by Go's runtime, emphasizing that developers should use channels for synchronization between coroutines.

As for threads, since the language level is not open, you can understand it as a multi-coroutine model. Several go routine can be created on one thread. Generally speaking, it will be created with the CPU The number of threads with the same number of cores is, of course, actually determined by the runtime.

Regarding the scheduling of goroutine, this is actually constantly evolving. I will only talk about the GMP model. Goroutine runs on M threads, and the current P will be checked every time a task is executed. The executable queue on the (processor) contains executable goroutines. Once there is no executable goroutine on the current P, it will steal the goroutine in the executable queue of another P.

Theoretically, the creation of goroutine is only limited by memory. Generally speaking, the maximum is 2KB. For a thread with 2MB space, theoretically, it can easily reach 1,000. Of course, this is only an ideal situation, so the OS The number of threads will not increase as the number of goroutines created increases. Thread scheduling is relatively performance-intensive for Go. Frequent switching of schedules will only exist between goroutines, and threads will only maintain the same number of active threads as the number of CPUs.

Related learning recommendations: Go language tutorial

The above is the detailed content of Is golang a multi-threaded mode?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:Is golang single-process?Next article:Is golang single-process?