Skip to content

Instantly share code, notes, and snippets.

@OutOfBrain
Created February 7, 2016 21:19
Show Gist options
  • Select an option

  • Save OutOfBrain/55c3ce018863cd4d51ef to your computer and use it in GitHub Desktop.

Select an option

Save OutOfBrain/55c3ce018863cd4d51ef to your computer and use it in GitHub Desktop.
Testing speed of channel lock and sync lock. Turns out channel lock is actually faster than sync lock (mutex).
package main
import (
"fmt"
"sync"
"testing"
)
var lockChannel chan bool = make(chan bool, 1)
var lockSync sync.Mutex
func countUpSync(i *int) {
lockSync.Lock()
*i++
lockSync.Unlock()
}
func countUpChannel(i *int) {
lockChannel <- true
*i++
<- lockChannel
}
func countUpBroken(i *int) {
*i++
}
func countUp(i *int, countupFunc func(*int)) {
for j:=0; j < 100000; j++ {
countupFunc(i)
}
g.Done()
}
var g sync.WaitGroup
func counterMain(countUpFunc func(*int)) {
g.Add(5)
i:=0
go countUp(&i, countUpFunc)
go countUp(&i, countUpFunc)
go countUp(&i, countUpFunc)
go countUp(&i, countUpFunc)
go countUp(&i, countUpFunc)
g.Wait()
fmt.Println(i)
}
func makeBenchmarkFunc(countUpFunc func(*int)) func(*testing.B) {
return func (b *testing.B) {
for i:= 0; i < b.N; i++ {
counterMain(countUpFunc)
}
}
}
func main() {
fmt.Println(testing.Benchmark(makeBenchmarkFunc(countUpBroken)))
fmt.Println(testing.Benchmark(makeBenchmarkFunc(countUpSync)))
fmt.Println(testing.Benchmark(makeBenchmarkFunc(countUpChannel)))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment