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

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.

主站蜘蛛池模板: 崇义县| 兴宁市| 灵台县| 沧源| 肇源县| 江源县| 巍山| 临沂市| 靖宇县| 黎平县| 沙河市| 淮滨县| 龙海市| 和静县| 焦作市| 集贤县| 东乡| 临汾市| 辽宁省| 仁怀市| 玉田县| 萍乡市| 儋州市| 西安市| 青铜峡市| 莱西市| 城口县| 江达县| 满洲里市| 绥化市| 平顺县| 吕梁市| 石景山区| 喜德县| 攀枝花市| 南木林县| 陇川县| 西盟| 舞钢市| 蒙山县| 汤原县|