SpinLock is a spin lock implementation in Go with exponential backoff and adaptive spinning.
To install the package, run:
go get github.com/daniel-hutao/[email protected]
Here is an example of how you can use the spinlock in your code:
package main
import (
"github.com/daniel-hutao/spinlock"
)
func main() {
var sl spinlock.SpinLock
sl.Lock()
// critical section here
sl.Unlock()
}
In this example, we first import the spinlock package and create a new SpinLock. Then, we use the Lock and Unlock methods to protect the critical section of our code. The critical section is where you would put the code that you want to protect with the lock.
We have conducted performance tests to compare the efficiency of our SpinLock implementation with the standard Mutex in Go. The tests were run on a MacBook Pro with an Apple M1 chip, 16GB of RAM.
$ go test -benchmem -run=^$ -bench ^BenchmarkSpinLock$ github.com/daniel-hutao/spinlock
goos: darwin
goarch: arm64
pkg: github.com/daniel-hutao/spinlock
=== RUN BenchmarkSpinLock
BenchmarkSpinLock
BenchmarkSpinLock-10 111107053 10.80 ns/op 0 B/op 0 allocs/op
PASS
ok github.com/daniel-hutao/spinlock 2.973s
$ go test -benchmem -run=^$ -bench ^BenchmarkMutex$ github.com/daniel-hutao/spinlock
goos: darwin
goarch: arm64
pkg: github.com/daniel-hutao/spinlock
=== RUN BenchmarkMutex
BenchmarkMutex
BenchmarkMutex-10 10366155 115.5 ns/op 0 B/op 0 allocs/op
PASS
ok github.com/daniel-hutao/spinlock 1.793s
Based on our tests, the SpinLock implementation performs significantly better than the standard Mutex in Go on a MacBook Pro with an Apple M1 chip. Specifically, operations on SpinLock are approximately an order of magnitude faster than those on Mutex.