Created
April 3, 2018 19:46
-
-
Save husobee/7e5b76f4bbfe539acf550f67a99d79fd to your computer and use it in GitHub Desktop.
rwmutex-v-chan
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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