Why so fast?

Why does GO support high concurrency, and how does it differ from Java multithreading?

Regular multithreading is scheduled directly by the CPU, and most of the time is spent on context switching, so co-routine is followed to reduce context switching.

GMP model

The secret to go’s high concurrency characteristics is the GMP model

M0 and G0

M0

M0 is the main thread numbered 0 after starting the program. The instance of this M is allocated on the global runtime. M0 does not need to be allocated on the heap. M0 performs initialization and starts the first G, after which M0 is the same as any other M.

G0

G0 is the first gourtine that is created every time an M is started. G0 is used only by the G responsible for scheduling. G0 does not point to any executable function, and each M has its own G0. The stack space of G0 is used during scheduling or system calls, and the G0 of global variables is the G0 of M0.

New coroutines are created and executed

When a new coroutine G is created, it is placed in the current local P queue first. If the local P queue is full, it is placed in the global G queue. P then schedules to the new G through G0, and then G0 exits and P executes the new G.

Spin thread

When the local P queue is empty, the current thread will become a spin thread. At this point, G0 continuously searches for the executable G(from the global G queue first), and then puts it into the local P queue, and THEN P switches to the newly found G to continue executing.

The work mechanism of stealing

The spin thread above preferentially looks for executable G from the global G queue, and when the global G queue is also empty, it steals G from other P queues and puts it into the local P queue.

Hand off mechanism

If G of the current thread makes a system blocking call, such as time.sleep, then the current thread releases P and transfers it to another idle thread. If there are no idle threads, a new thread is created

The local P queue is full

If the local P queue is full, disarrange the first half of the local P queue and put it into the global G queue with the new G

Information recommendation: www.kancloud.cn/aceld/golan…