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

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.

主站蜘蛛池模板: 民丰县| 大城县| 常州市| 厦门市| 尚义县| 舟山市| 彩票| 巴东县| 门头沟区| 年辖:市辖区| 大余县| 营山县| 定边县| 大连市| 儋州市| 阿图什市| 泰宁县| 德保县| 清水县| 承德市| 贡觉县| 阜新市| 乌拉特前旗| 类乌齐县| 恭城| 海林市| 阆中市| 潼关县| 福海县| 大足县| 辰溪县| 桐乡市| 四子王旗| 古交市| 正安县| 望谟县| 古田县| 玉田县| 克拉玛依市| 涿州市| 射洪县|