- 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.
- INSTANT Mock Testing with PowerMock
- Learning Java Functional Programming
- LabVIEW 2018 虛擬儀器程序設計
- Python機器學習:數據分析與評分卡建模(微課版)
- DevOps入門與實踐
- Python Deep Learning
- Practical DevOps
- Implementing Cisco Networking Solutions
- 青少年學Python(第1冊)
- 劍指Java:核心原理與應用實踐
- HTML5從入門到精通(第4版)
- Python深度學習:模型、方法與實現
- Mastering Business Intelligence with MicroStrategy
- ServiceNow:Building Powerful Workflows
- 小程序,巧應用:微信小程序開發實戰(第2版)