4 ms·
+1 for the aggressive approach, mutexes are very fast in go. I got curious and wrote a quick little benchmark test: $ cat bench_test.go package main
by jaytaylor 11y ago
+1 for the aggressive approach, mutexes are very fast in go.
I got curious and wrote a quick little benchmark test:
$ cat bench_test.go
package main
import (
"sync"
"testing"
)
func BenchmarkMutex(b *testing.B) {
var m sync.Mutex
for n := 0; n < b.N; n++ {
m.Lock()
m.Unlock()
}
}
$ go test -v -bench=. bench_test.go
BenchmarkMutex 50000000 24.0 ns/op
ok command-line-arguments 1.235s
A set of mutex.Lock() & .Unlock() calls takes only 24.0ns on average to complete.
Thus it's possible to lock/unlock more than 41 million times per second on the puny 2011 MacBook Air I used for this.
My .02c:
The post seems like a case of premature optimization.
Resource bottlenecks due to too much mutex locking in go does not seem like a case that will be commonly hit.
With infinite potential bottlenecks, I don't like to spend my time worrying and fussing over things that are:
A) Not yet a problem.
B) Unlikely to ever be a problem or give me grief.
Worrying about the overhead cost of locking falls squarely into just such a category.
- millstone 11y agoHere's the mutex source: https://golang.org/src/sync/mutex.go https://golang.org/src/sync/mutex.go . The fast path is just a CAS, which of course is going to be fast. But it's also important to know how it performs under contention.
- pcwalton 11y agoBe careful with that benchmark. It's very vulnerable to SROA and constant propagation optimizing it away to nothing. (Doesn't look like Go's compiler optimizations are able to do that based on those numbers, but a modern optimizer will.)
- jsprogrammer 11y agoThis has no contention and is essentially a no-op? Or do I not understand go?
- pcwalton 11y agoIt is a no-op, but Golang's Plan 9-based compilers don't do much optimization, so they aren't able to eliminate it.
- AYBABTME 11y agoTry again with many goroutines trying to lock/unlock in parallel (and GOMAXPROCS>1), the results are quite different!