Go RWMutex 读写锁
Go About 793 wordsRWMutex
可并行读,读写互斥。有写时,所有读都暂停。
类似于Java
中的ReentrantReadWriteLock
。
代码
var rwMutex sync.RWMutex
func main() {
amount := 0
for i := 0; i < 10; i++ {
go Read(&amount)
}
for i := 0; i < 10; i++ {
go Write(&amount)
}
time.Sleep(time.Second * 3)
Read(&amount)
}
func Read(amount *int) {
rwMutex.RLock()
defer rwMutex.RUnlock()
println(time.Now().String(), "#", *amount)
}
func Write(amount *int) {
rwMutex.Lock()
defer rwMutex.Unlock()
*amount += 1
}
读锁
RLock
上读锁,RUnlock
解除读锁。
func Read(amount *int) {
rwMutex.RLock()
defer rwMutex.RUnlock()
println(time.Now().String(), "#", *amount)
}
写锁
Lock
上写锁,Unlock
解除写锁。
func Write(amount *int) {
rwMutex.Lock()
defer rwMutex.Unlock()
*amount += 1
}
Views: 676 · Posted: 2023-10-07
————        END        ————
Give me a Star, Thanks:)
https://github.com/fendoudebb/LiteNote扫描下方二维码关注公众号和小程序↓↓↓
Loading...