course/sync/rwmutex.go

54 lines
994 B
Go
Raw Normal View History

2024-07-09 00:38:00 +08:00
package main
import (
"fmt"
"sync"
"time"
)
// 读写互斥锁,读的时候远远大于写的场景
// rwlock
// 当读的时候加读锁,写的时候加写锁。和互斥锁相比性能差很多
// 当持有写锁所有的goroutine都需要等待写锁解锁不能读也不能写当持有读锁所有goroutine仍然能够读访问共享资源但不允许写
var (
v = 0
locker sync.Mutex
w sync.WaitGroup
rwlocker sync.RWMutex
)
func read() {
defer w.Done()
locker.Lock()
//rwlocker.RLock()
fmt.Println(v)
time.Sleep(time.Millisecond * 1)
locker.Unlock()
//rwlocker.RUnlock()
}
func write() {
defer w.Done()
locker.Lock()
//rwlocker.Lock()
v += 1
time.Sleep(time.Millisecond * 5)
locker.Unlock()
//rwlocker.Unlock()
}
func main() {
start := time.Now()
for i := 0; i < 10; i++ {
w.Add(1)
go write()
}
time.Sleep(time.Second)
for i := 0; i < 1000; i++ {
w.Add(1)
go read()
}
w.Wait()
fmt.Println(time.Now().Sub(start))
}