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

The read-write mutex

Go also supports a read-write lock. A read-write lock differentiates between read and write operations. So, whenever you only perform concurrent read operations, the goroutines won't block. However, whenever you perform a write operation, all other reads and writes get blocked until the write lock is released. As always, this is best explained with an example, such as the following code:

var myRWMutex = &sync.RWMutex{}

A read-write lock in Go is represented by a pointer to a Go struct of the sync.RWMutex type, which is what we initialized in the preceding code snippet.

To perform a read operation, we make use of the RLock() and RUnlock() methods of the Go struct:

myRWMutex.RLock()
fmt.Println(myMap[1])
myRWMutex.RUnlock()

To perform a write operation, we make use of the Lock() and Unlock() methods:

myRWMutex.Lock()
myMap[2] = 200
myRWMutex.Unlock()

The *sync.RWMutex type can be found all over the place in Go's standard package.

主站蜘蛛池模板: 博罗县| 宽城| 辽宁省| 阿拉善左旗| 建阳市| 历史| 长汀县| 永善县| 深泽县| 虞城县| 赤壁市| 六枝特区| 威海市| 沭阳县| 襄樊市| 南投县| 丰城市| 南乐县| 竹山县| 齐河县| 定州市| 隆林| 桂林市| 清水河县| 柏乡县| 论坛| 华池县| 绿春县| 浮梁县| 永和县| 孟连| 玛多县| 井陉县| 黄龙县| 广元市| 玛多县| 肥城市| 永登县| 舞阳县| 兴业县| 冀州市|