Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
rwmutex-v-chan
package main
import (
"sync"
"testing"
)
type stuff struct {
ret chan string
input string
op int
}
var (
m = map[string]string{
"test": "test",
}
mu = new(sync.RWMutex)
)
func doStuff(req chan stuff) {
for {
select {
case stuff := <-req:
if stuff.op == 0 {
//read from map
stuff.ret <- m[stuff.input]
} else if stuff.op == 1 {
//write to map
m[stuff.input] = stuff.input
stuff.ret <- stuff.input
}
}
}
}
func BenchmarkChanMixReadWrite(b *testing.B) {
// run the Fib function b.N times
read := make(chan stuff, 1000)
go doStuff(read)
for n := 0; n < b.N; n++ {
go func() {
var req = stuff{input: "test", ret: make(chan string)}
if n%10 == 0 {
// write to map
req.op = 1
} else {
// read from map
req.op = 0
}
read <- req
_ = <-req.ret
}()
}
}
func BenchmarkMuxtexMixReadWrite(b *testing.B) {
// run the Fib function b.N times
for n := 0; n < b.N; n++ {
go func() {
if n%10 == 0 {
mu.Lock()
m["test"] = "test"
mu.Unlock()
} else {
mu.RLock()
_ = m["test"]
mu.RUnlock()
}
}()
}
}
//go test -bench Benchmark*
//goos: darwin
//goarch: amd64
//pkg: chanvrwmutex
//BenchmarkChanMixReadWrite-8 1000000 2311 ns/op
//BenchmarkMuxtexMixReadWrite-8 10000000 206 ns/op
//PASS
//ok chanvrwmutex 6.236s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment