For a long time to think that reading and writing less scenes, read-write lock performance is necessarily better than the mutex, but the opposite is true
No nonsense, first a test code
Func Main () {
var w = &sync. waitgroup{}
var num = 50000000
var c = make (chan int, 3000)
var rwmutextmp = Newrwmutex ()
W.add (num)
T1: = time. Now ()
For I: = 0; i < num; i++ {
C <-0
Go func (index int) {
Defer W.done ()
_ = Rwmutextmp.get (index)
Fmt. Println (value)
<-c
} (i)
}
W.wait ()
T2: = time. Now ()
var mutextmp = Newmutex ()
W.add (num)
T3: = time. Now ()
For I: = 0; i < num; i++ {
C <-0
Go func (index int) {
Defer W.done ()
T: = Mutextmp.get ()
_, _ = T[index]
Fmt. Println (OK)
<-c
} (i)
}
W.wait ()
T4: = time. Now ()
Fmt. Println ("Rwmutex cost:", T2. Sub (T1). String ())
Fmt. PRINTLN ("Mutex cost:", T4. Sub (T3). String ())
}
Type Rwmutex struct {
Mu *sync. Rwmutex
Ipmap Map[int]int
}
Type Mutex struct {
Mu *sync. Mutex
Ipmap Map[int]int
}
Func (t *rwmutex) get (i int) int {
T.mu.rlock ()
Defer T.mu.runlock ()
return T.ipmap[i]
}
Func (t *mutex) get () Map[int]int {
T.mu.lock ()
Defer T.mu.unlock ()
Return T.ipmap
}
Func Newrwmutex () *rwmutex {
var t = &rwmutex{}
T.mu = &sync. rwmutex{}
T.ipmap = Make (map[int]int, 100)
For I: = 0; I < 100; i++ {
T.ipmap[i] = 0
}
Return T
}
Func Newmutex () *mutex {
var t = &mutex{}
T.mu = &sync. mutex{}
T.ipmap = Make (map[int]int, 100)
For I: = 0; I < 100; i++ {
T.ipmap[i] = 0
}
Return T
}
Each plus lock 50 million times, the time comparison is as follows:
Go Run test_rwmutex_mutex.go
Rwmutex cost:22.403487195s
Mutex cost:21.636404963s
Go Run test_rwmutex_mutex.go
Rwmutex cost:22.3359224s
Mutex cost:21.931208658s
In some scenarios, mutexes are faster than read and write locks!!!