Go uses channels to realize the pit of coroutine data communication

Go concurrency is built on CSP through channels. It uses channels to make it easier and safer to coordinate goroutines than to synchronize on shared data. The old saying is "Don't communicate through shared memory; instead, share memory through communication."

Go has no way to obtain immutable data structures. This means that once we send a pointer on the channel, gameover: because mutable data is shared between concurrent processes, it will cause data confusion

Of course, the structure of a channel is to assign the value transmitted by the channel (not the pointer), but we must ensure that the data type sent to the channel is immutable;

We must pay attention to those references that are not deeply copied, including slices and maps, which are essentially mutable, the same as the struct field of the interface type: they are pointers, and any mutable methods defined by the interface are open to race conditions.

Therefore, although channels seem to make concurrent programming easy, they cannot prevent race conditions on shared data. The variability of slices and maps themselves makes this more likely.

Guess you like

Origin blog.csdn.net/QiuHaoqian/article/details/108997438