Channels

在《The Little Go Book》里有关于 channel 的一段话:

In other words, a goroutine that has data can pass it to another goroutine via a channel. The result is that, at any point in time, only one goroutine has access to the data.

这给我一个启发,突然理解了 channel 的意义。

 

因为使用像 goroutine 之类的 concurrency 功能时,最大的难题就是处理各个 goroutine 对数据的访问(比如要避免同时对一个数据进行写操作),也就是说,需要确保一个数据在同一个时间点只被一个 goroutine 访问。

 

而 channel 的主要功能之一正是解决这个问题,即,其主要作用之一是确保数据访问的唯一性。

 

假设有两个 goroutine (A和B), 它们之间有一个 channel (C), 有一个数据 (V) 通过 C 来传递,那么,根据 channel 的功能可知: V 要么在 A 那里,要么在 B 那里,不会出现 A 和 B 同时访问 V 的情况。 

 

posted @ 2017-04-23 00:12  AHUI-2017  阅读(234)  评论(0编辑  收藏  举报