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

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.

主站蜘蛛池模板: 金塔县| 西乌| 贡觉县| 五指山市| 申扎县| 班玛县| 靖州| 九龙县| 衡东县| 乐清市| 文化| 华池县| 穆棱市| 南乐县| 榆林市| 呼和浩特市| 兰西县| 漯河市| 新野县| 应城市| 闽侯县| 无棣县| 肥东县| 辽中县| 雷州市| 万安县| 拉萨市| 镇远县| 平阴县| 永福县| 新干县| 宜州市| 星座| 上杭县| 禄丰县| 灵璧县| 平南县| 长沙县| 万山特区| 通州市| 古交市|