- Add number to 10000.
- RWLock (Use Lock/Unlock to read): 19ms, 92202 read count
- RWLock (Use RLock/RUnlock to read): 597ms, 4789798 read count
- We can say read lock get more chances to read.. overall make write become slower because limited CPU Core Size (8 in my machine)
- Here is code for copy/paste and try
package main
import (
"fmt"
"sync"
"sync/atomic"
"time"
)
var rc int32
var n int
var m sync.RWMutex
var wg sync.WaitGroup
func main() {
from := time.Now()
for i := 0; i < 100; i++ {
round := 100
wg.Add(round)
go func() {
for {
m.RLock()
atomic.AddInt32(&rc, 1)
fmt.Sprint(n)
m.RUnlock()
}
}()
go func() {
for i := 0; i < round; i++ {
m.Lock()
n++
m.Unlock()
wg.Done()
}
}()
}
wg.Wait()
duration := time.Now().Sub(from)
fmt.Println("readCount:", rc, "n:", n, "duration:", duration)
}
沒有留言:
張貼留言