- Hands-On Full Stack Development with Go
- Mina Andrawos
- 152字
- 2021-07-02 12:33:35
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.
- Android Wearable Programming
- GeoServer Cookbook
- CMDB分步構建指南
- 微信小程序入門指南
- Java程序設計
- Scientific Computing with Scala
- 精通Linux(第2版)
- Web性能實戰
- 進入IT企業必讀的324個Java面試題
- AMP:Building Accelerated Mobile Pages
- Spark技術內幕:深入解析Spark內核架構設計與實現原理
- 從零開始構建深度前饋神經網絡:Python+TensorFlow 2.x
- Learning Cocos2d-JS Game Development
- 深入理解Kafka:核心設計與實踐原理
- Parallel Programming with Python