- 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.
- Spring Boot 2實(shí)戰(zhàn)之旅
- 多媒體CAI課件設(shè)計(jì)與制作導(dǎo)論(第二版)
- JBoss Weld CDI for Java Platform
- 國(guó)際大學(xué)生程序設(shè)計(jì)競(jìng)賽中山大學(xué)內(nèi)部選拔真題解(二)
- 軟件測(cè)試項(xiàng)目實(shí)戰(zhàn)之性能測(cè)試篇
- Python高級(jí)編程
- Learning AndEngine
- 嚴(yán)密系統(tǒng)設(shè)計(jì):方法、趨勢(shì)與挑戰(zhàn)
- 網(wǎng)站構(gòu)建技術(shù)
- Haxe Game Development Essentials
- 飛槳PaddlePaddle深度學(xué)習(xí)實(shí)戰(zhàn)
- bbPress Complete
- Mathematica Data Analysis
- Learning Unreal Engine Android Game Development
- GameMaker Essentials