Co-process
The execution body is an abstract concept, and there are many concepts that correspond to the operating system level, such as the process in which the operating system is in charge, the threads within the process (thread), and the processes within the process (Coroutine, also known as lightweight threads). Compared to traditional threads and processes, The biggest advantage of the process is its "lightweight", which makes it easy to create millions without causing system resources to run out, while threads and processes are typically no more than 10,000, which is why the process is called a lightweight thread.
The Go language supports lightweight threading at the language level, and all system invoke operations provided by the Goroutine,go language standard library will give the CPU to the other goroutine, which makes the switching of lightweight threads independent of the system's threads and processes, and does not depend on the number of cores in the CPU.
Go language execution mechanism:
The Go program starts with the initialization of the main package and executes the main () function, and when the main () function returns, the program exits, and the program does not wait for other goroutine (non-primary goroutine) to end.
To let the main function wait for all goroutine to exit and then return, how do you know that all goroutine have exited? This leads to the problem of communication between multiple goroutine.
Concurrent communication:
There are two common models of concurrent communication:
Shared data refers to multiple concurrent units holding a reference to the same data, respectively, to share the data. The data being shared may have many forms, such as memory data blocks, disk files, network data, etc. common memory sharing.
The message mechanism considers that each concurrent unit is self-contained, independent, and has its own variables, but these variables are different among the different concurrent units. There is only one input and output for each concurrent unit, and that is the message. A bit like the concept of processes, each process is not disturbed by other processes, It can only do its own work, the different processes rely on messages to communicate, they do not share memory.
The message communication mechanism provided by the go language is called the channel.
Go concurrency programming (2)