java - 如何理解“不要通过共享内存来通信,而应该通过通信来共享内存”?
大家讲道理
大家讲道理 2017-04-18 10:53:51
0
4
1784

不要通过共享内存来通信,而应该通过通信来共享内存

这是一句风靡golang社区的经典语,对于刚接触并发编程的人,该如何理解这句话?

大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

reply all(4)
Ty80

https://blog.golang.org/share...

This article makes it clearer. If you use shared memory, in order to handle race conditions in a multi-threaded scenario, you need to lock it, which is more troublesome to use. In addition, using too many locks can easily make the code logic of the program difficult to understand, and can easily cause the program to deadlock. After the deadlock occurs, it is very difficult to troubleshoot the problem, especially when many locks exist at the same time.

The channel of the go language ensures that only one goroutine can access the data inside at the same time, providing developers with an elegant and simple tool. Therefore, the native method of go is to use channel to communicate instead of using shared memory to communicate.

Peter_Zhu

I think the former means that everyone maintains a state, and the latter means that everyone maintains a copy of the state.

洪涛

Shared memory will involve multiple threads accessing and modifying data at the same time. To ensure the security and visibility of the data, locking will be performed. Locking will turn parallelism into serialization, and the CPU will also be busy with threads grabbing locks. It is better to change the way and make a copy of the data. Each thread has its own. As long as one thread completes one thing, other threads do not have to grab the lock. This is a communication method. The shared data is handed over in the form of notification. Threads to achieve concurrency

伊谢尔伦

In fact, if you understand it from a distributed perspective, it will be more clear.

For example, if two processes ab operate on the same message queue together, then if shared memory is used, the two processes must be limited to the same physical machine, then the meaning of communication will be greatly reduced.

If at the time of design, only read and write interfaces are provided for the message queue, and you don’t have to worry about the internal implementation at all, it will seem like the message queue is like shared memory. However, your message queue can communicate using sockets.

So, the above sentence, don’t use shared memory to implement communication, means not to limit the program to a single machine from the beginning, but to use communication, that is, to encapsulate the internal implementation and provide interfaces to perform corresponding operations

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!