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

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.

主站蜘蛛池模板: 阳原县| 博罗县| 新河县| 长顺县| 酉阳| 如皋市| 定安县| 建水县| 措勤县| 北辰区| 金华市| 奉新县| 蓬溪县| 岳阳县| 金华市| 平泉县| 凤庆县| 桃江县| 兴化市| 江津市| 奎屯市| 天柱县| 田东县| 逊克县| 伊金霍洛旗| 建德市| 景东| 德阳市| 通化市| 离岛区| 东兴市| 新疆| 河北省| 屏东市| 溆浦县| 泽州县| 华容县| 鲜城| 南京市| 荆门市| 谢通门县|