Created
September 19, 2018 07:40
-
-
Save woodsaj/ffb18944042ed34e57a5ca38464195d7 to your computer and use it in GitHub Desktop.
Benchmark to compare shared locks vs per-thread locks
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 input | |
import ( | |
"fmt" | |
"sync" | |
"testing" | |
) | |
// simple datastruct to provide a lock around an int variable | |
type Data struct { | |
sync.RWMutex | |
D int | |
} | |
func (d *Data) Get() int { | |
d.RLock() | |
defer d.RUnlock() | |
return d.D | |
} | |
func doWork(pb *testing.PB, d *Data) { | |
for pb.Next() { | |
if d.Get() > 1 { | |
fmt.Printf("data is > 1") | |
} | |
} | |
} | |
func BenchmarkSharedLock(b *testing.B) { | |
b.SetParallelism(8) | |
d := &Data{} | |
b.RunParallel(func(pb *testing.PB) { | |
doWork(pb, d) | |
}) | |
} | |
func BenchmarkIsolatedLock(b *testing.B) { | |
b.SetParallelism(8) | |
b.RunParallel(func(pb *testing.PB) { | |
d := &Data{} | |
doWork(pb, d) | |
}) | |
} |
Author
woodsaj
commented
Sep 19, 2018
•
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment