Go的sync.RWMutex(六)
作者:互联网
RWMutex
RWMutex有两种锁写锁和读锁,用法也有不同,首先读锁可以同时加多个,但是写锁就不行 只能1个
该锁可以加多个读锁或者一个写锁,其经常用于读次数远远多于写次数的场景.
原则
- 1、读锁的时候无需等待读锁的结束
- 2、读锁的时候要等待写锁的结束
- 3、写锁的时候要等待读锁的结束
- 4、写锁的时候要等待写锁的结束
操作
- RLock() //读锁定
- RUnlock() //读解锁
- Lock() //写锁定
- Unlock() //写解锁
实例
package main
import (
"sync"
"time"
)
var m *sync.RWMutex
func main() {
m = new(sync.RWMutex)
// 多个同时读
go read(1)
go read(2)
time.Sleep(2*time.Second)
}
func read(i int) {
println(i,"read start")
m.RLock()
println(i,"reading")
time.Sleep(1*time.Second)
m.RUnlock()
println(i,"read over")
}
运行结果:
1 read start
1 reading
2 read start
2 reading
1 read over
2 read over
可以看出1 读还没有结束,2已经在读 所以读锁之间不影响
package main
import (
"sync"
"time"
)
var m *sync.RWMutex
func main() {
m = new(sync.RWMutex)
// 写的时候啥也不能干
go write(1)
go read(2)
go write(3)
time.Sleep(2*time.Second)
}
func read(i int) {
println(i,"read start")
m.RLock()
println(i,"reading")
time.Sleep(1*time.Second)
m.RUnlock()
println(i,"read over")
}
func write(i int) {
println(i,"write start")
m.Lock()
println(i,"writing")
time.Sleep(1*time.Second)
m.Unlock()
println(i,"write over")
}
1 write start
1 writing
2 read start
3 write start
1 writing over
2 reading
2 read over
3 writing
3 write over
可以看出写锁会对于读锁进行阻碍 在写锁的时候进入不到读锁
标签:RWMutex,start,read,over,sync,println,读锁,time,Go 来源: https://blog.csdn.net/fujian9544/article/details/100538286