golang读写锁RWMutex
读写锁是针对读写的互斥锁
基本遵循两大原则:
1、可以随便读,多个goroutine同时读
2、写的时候,啥也不能干。不能读也不能写
RWMutex提供了四个方法:
func (*RWMutex) Lock // 写锁定
func (*RWMutex) Unlock // 写解锁
func (*RWMutex) RLock // 读锁定
func (*RWMutex) RUnlock // 读解锁
一、随便读
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
posted on 2021-09-09 11:06 ExplorerMan 阅读(438) 评论(0) 编辑 收藏 举报