Skip to content

Instantly share code, notes, and snippets.

@maciej
Last active July 12, 2020 09:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maciej/8b3beecfb32ce936e62f2bfb6497a7ce to your computer and use it in GitHub Desktop.
Save maciej/8b3beecfb32ce936e62f2bfb6497a7ce to your computer and use it in GitHub Desktop.
Signalling concurrent initialisation in Go
package main
import (
"sync"
"sync/atomic"
"testing"
)
func BenchmarkClosedChannel(b *testing.B) {
c := make(chan struct{})
close(c)
b.ResetTimer()
for i := 0; i < b.N; i++ {
<-c
}
}
func BenchmarkWaitGroup(b *testing.B) {
wg := new(sync.WaitGroup)
// Imitate a real-world scenario
// it's used for init signal, so we first start with "uninitialized" state
wg.Add(1)
wg.Done()
b.ResetTimer()
for i := 0; i < b.N; i++ {
wg.Wait()
}
}
func BenchmarkAtomicLoad(b *testing.B) {
const InitializedState = 1
ap := new(uint64)
atomic.StoreUint64(ap, InitializedState)
b.ResetTimer()
for i := 0; i < b.N; i++ {
if state := atomic.LoadUint64(ap); state != InitializedState {
// this can be implemented for example by waiting on a channel close
panic("wait condition code goes here")
}
}
}
# 2017 MacBook Pro 15'
# 2,8 GHz Quad-Core Intel Core i7
# Go 1.14.4
BenchmarkClosedChannel
BenchmarkClosedChannel-8 52708377 22.2 ns/op
BenchmarkWaitGroup
BenchmarkWaitGroup-8 364102297 3.18 ns/op
BenchmarkAtomicLoad
BenchmarkAtomicLoad-8 1000000000 0.598 ns/op
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment