This is a creation in Article, where the information may have evolved or changed. Copyright belongs to the author.
Commercial reprint please contact the author for authorization, non-commercial reprint please specify the source.
Author: Qi Wang
Links: http://www.zhihu.com/question/27305094/answer/36076688
Source: Know
In the recent process of understanding the go language, the knowledge of many language features involves the running mechanism of Go runtime. After searching the internet, I didn't see much valuable information. There seems to be no other way than to study the source code. But I still found a paper titled: Analysis of the Go Runtime Scheduler, some of which were introduced to go runtime. Here is my understanding to tidy up.
First, this diagram depicts the relationship between the Go Language program, the runtime, and the operating system.
Among them, runtime management task scheduling, garbage collection and operating environment. You know that the Go Language program is compiled for machine code execution. At the same time, go offers some advanced features such as Goroutine, channel, and garbage collection. These advanced features require a runtime support. Before 1.4, runtime was written by the C language, (according to the Go Dev Team plan, version 1.5 will remove the C code, runtime will be completely done by the go language.) Either way, runtime and user-compiled code are linker statically linked to form an executable file. This file is a standalone executable file of user space from the operating system perspective.
From the point of view of operation, this file is composed of 2 parts, part of the user's code, and the other part is runtime. Runtime manages Goroutine, channel, and other advanced functions through interface function calls. Calls to the operating system API originating from user code are intercepted and processed by the runtime.
An important part of Go runtime is the Goroutine scheduler. He is responsible for tracking, scheduling each goroutine run, and actually assigning a thread to the thread pool that the application's process belongs to to perform this goroutine. Therefore, similar to Java thread and OS thread mapping concepts in Java virtual machines, each goroutine is assigned to one OS thread to run.
In fact, the go runtime is very complex, and when the 1.5 version comes out, read the code carefully, then C's code should no longer exist. will be easier to understand.