官术网_书友最值得收藏!

Go channels

An important question can now be addressed; what if we need to share a piece of data between two different goroutines?

In programs that make use of multiple threads, the common approach to share data between different threads is to lock the variables that are shared between the threads. This is typically known as the sharing memory approachThe following diagram demonstrates how two threads will share memory, by sharing a variable called X:

In Go, there is a very popular motto:

"Do not communicate by sharing memory; instead, share memory by communicating."

What does that mean? It simply means that Go does not typically prefer sharing memory (there are exceptions, however) between threads through the lock approach. Instead, Go prefers to communicate the data from one goroutine to another. This communicate part is achieved through the Go channels. The following diagram demonstrates how this looks visually:

Let's take a look at regular and buffered channels in the next sections.

主站蜘蛛池模板: 年辖:市辖区| 大港区| 吉安市| 车险| 宁河县| 洞口县| 双辽市| 堆龙德庆县| 乐东| 高要市| 江山市| 太白县| 五常市| 革吉县| 宁陕县| 新安县| 丹棱县| 府谷县| 安庆市| 泌阳县| 海原县| 桦川县| 三都| 舟曲县| 读书| 喀喇沁旗| 嘉兴市| 来安县| 沙雅县| 永济市| 长治县| 台东县| 隆子县| 广河县| 郸城县| 宁化县| 原阳县| 清水河县| 灵台县| 资兴市| 依安县|