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

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.

主站蜘蛛池模板: 柳州市| 德昌县| 喀喇沁旗| 垦利县| 英德市| 枣庄市| 同江市| 榆树市| 石屏县| 沂南县| 绥中县| 江油市| 平度市| 民勤县| 海林市| 仪陇县| 大石桥市| 新建县| 三穗县| 固安县| 施甸县| 隆化县| 江门市| 司法| 高安市| 德阳市| 德州市| 梁山县| 聂拉木县| 晋州市| 额尔古纳市| 东安县| 电白县| 勃利县| 卓尼县| 蓬莱市| 聊城市| 晋州市| 深圳市| 望城县| 肥东县|