Skip to content

Instantly share code, notes, and snippets.

@replay
Created July 22, 2019 13:26
Show Gist options
  • Save replay/81f90623c17c7b5e83a951a1f0018a58 to your computer and use it in GitHub Desktop.
Save replay/81f90623c17c7b5e83a951a1f0018a58 to your computer and use it in GitHub Desktop.
Compare global lock to atomics
import (
"context"
"sync"
"sync/atomic"
"testing"
"golang.org/x/sync/errgroup"
)
func BenchmarkAtomicIncDec(b *testing.B) {
var value uint32
const increase = 1
const decrease = 2
actions := make(chan int, 10)
rootCtx, cancel := context.WithCancel(context.Background())
group, ctx := errgroup.WithContext(rootCtx)
for i := 0; i < 10; i++ {
group.Go(func() error {
for {
select {
case action := <-actions:
switch action {
case increase:
atomic.AddUint32(&value, 1)
case decrease:
atomic.AddUint32(&value, ^uint32(0))
}
case <-ctx.Done():
return nil
}
}
return nil
})
}
for i := 0; i < b.N; i++ {
actions <- increase
actions <- decrease
}
cancel()
}
func BenchmarkLockIncDec(b *testing.B) {
var value uint32
globalLock := sync.RWMutex{}
const increase = 1
const decrease = 2
actions := make(chan int, 10)
rootCtx, cancel := context.WithCancel(context.Background())
group, ctx := errgroup.WithContext(rootCtx)
for i := 0; i < 10; i++ {
group.Go(func() error {
for {
select {
case action := <-actions:
switch action {
case increase:
globalLock.Lock()
value++
globalLock.Unlock()
case decrease:
globalLock.Lock()
value--
globalLock.Unlock()
}
case <-ctx.Done():
return nil
}
}
return nil
})
}
for i := 0; i < b.N; i++ {
actions <- increase
actions <- decrease
}
cancel()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment