Skip to content

Instantly share code, notes, and snippets.

@armando-couto
Created March 2, 2022 02:50
Show Gist options
  • Save armando-couto/c00a43c3f841045bdac4d06e74c42f7a to your computer and use it in GitHub Desktop.
Save armando-couto/c00a43c3f841045bdac4d06e74c42f7a to your computer and use it in GitHub Desktop.
The sync.RWMutex is conceptually the same thing as a Mutex: it guards access to memory; however, RWMutex gives you a little bit more control over the memory. You can request a lock for reading, in which case you will be granted access unless the lock is being held for writing. This means that an arbitrary number of readers can hold a reader lock…
package main
import (
"fmt"
"math"
"os"
"sync"
"text/tabwriter"
"time"
)
func main() {
producer := func(wg *sync.WaitGroup, l sync.Locker) {
defer wg.Done()
for i := 5; i > 0; i-- {
l.Lock()
l.Unlock()
time.Sleep(1)
}
}
observer := func(wg *sync.WaitGroup, l sync.Locker) {
defer wg.Done()
l.Lock()
defer l.Unlock()
}
test := func(count int, mutex, rwMutex sync.Locker) time.Duration {
var wg sync.WaitGroup
wg.Add(count + 1)
beginTestTime := time.Now()
go producer(&wg, mutex)
for i := count; i > 0; i-- {
go observer(&wg, rwMutex)
}
wg.Wait()
return time.Since(beginTestTime)
}
tw := tabwriter.NewWriter(os.Stdout, 0, 1, 2, ' ', 0)
defer tw.Flush()
var m sync.RWMutex
fmt.Fprintf(tw, "Readers\tRWMutext\tMutex\n")
for i := 0; i < 20; i++ {
count := int(math.Pow(2, float64(i)))
fmt.Fprintf(
tw,
"%d\t%v\t%v\n",
count,
test(count, &m, m.RLocker()),
test(count, &m, &m),
)
}
}
@armando-couto
Copy link
Author

Readers RWMutext Mutex
1 54.666µs 26.36µs
2 24.341µs 5.886µs
4 6.454µs 3.393µs
8 21.377µs 29.507µs
16 39.863µs 38.565µs
32 56.348µs 30.771µs
64 90.52µs 39.657µs
128 75.669µs 60.326µs
256 75.186µs 131.216µs
512 269.783µs 205.489µs
1024 500.515µs 401.603µs
2048 853.739µs 816.401µs
4096 1.426848ms 1.530207ms
8192 2.901851ms 2.859511ms
16384 5.433534ms 4.660361ms
32768 9.736846ms 9.606706ms
65536 18.027942ms 17.034139ms
131072 35.323507ms 33.591433ms
262144 74.472261ms 61.335668ms
524288 142.829393ms 121.807634ms

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment