Created
July 22, 2019 13:26
-
-
Save replay/81f90623c17c7b5e83a951a1f0018a58 to your computer and use it in GitHub Desktop.
Compare global lock to atomics
This file contains hidden or 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
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