" do not communicate by sharing memory, to share memory through communication " is a very classic word in the go community, but how do we understand this sentence?
The Go Language (goroutine) is developed from a process, a thread, and is lighter than a process thread, but is all for concurrency. Since it is concurrent, it is inevitable that there will be multiple different concurrent entities to propagate or exchange information, that is, communication. To understand the phrase " do not communicate through shared memory to share memory through communication ," we need to learn from the comparison of communication with process threads.
Because the communication between the go is in the same process, there is no need to compare with interprocess communication, just compare with interprocess communication. Communication between Threads
Two or more threads to propagate or exchange information, the usual practice is:
-Assign a shared variable, and multiple threads get or modify the variable to exchange information. A variable is essentially a shared memory.
-through queues to achieve consumer and producer patterns to communicate. The queue is essentially the same block of memory that is shared between threads. Of course, you can also understand the queue as a shared variable.
-thread synchronization mechanism to control the operation between threads, such as synchronization locks, semaphores, condition variables. Shared variables and queues also require a thread synchronization mechanism to ensure data and communication are correct.
The information exchanged between threads in general thread synchronization is only control information, for example, a thread releases a lock, B threads can acquire a lock and start running, which does not involve exchanging data. Data exchange is mainly through shared memory (shared variables or queues), in order to ensure data security and correctness, shared memory will need to lock and other thread synchronization mechanism. Thread synchronization is particularly cumbersome to cause deadlocks, and too many locks can cause thread congestion and the extra overhead of context switching in this process. go in shared memory through channel
In the
Go language, to pass a data to another goroutine (coprocessor), you can encapsulate the data into an object, then pass the pointer of the object into a channel, and the other goroutine read the pointer from the channel. and processes the memory object it points to. Go from the language level to ensure that the same time only one goroutine can access the data inside the channel, providing developers with an elegant and simple tool, so go is to use channel to communicate, through communication to pass the memory data, Allows the memory data to be passed in different goroutine instead of using shared memory to communicate.