Skip to content

Commit

Permalink
using a struct for the spinlock and cleaned up the comments a little.
Browse files Browse the repository at this point in the history
  • Loading branch information
OneOfOne committed Sep 6, 2014
1 parent db5002c commit 594f507
Showing 1 changed file with 10 additions and 7 deletions.
17 changes: 10 additions & 7 deletions sync/spinlock.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,25 +8,28 @@ import (
var state = [2]string{"Unlocked", "Locked"}

// SpinLock implements a simple atomic spin lock, the zero value for a SpinLock is an unlocked spinlock.
type SpinLock uint32
type SpinLock struct {
l uint32
}

// Lock locks sl. If the lock is already in use, the calling goroutine blocks until the lock is freed.
// Lock locks sl. If the lock is already in use, the caller blocks until Unlock is called
func (sl *SpinLock) Lock() {
for !atomic.CompareAndSwapUint32((*uint32)(sl), 0, 1) {
for !atomic.CompareAndSwapUint32(&sl.l, 0, 1) {
runtime.Gosched() //allow other goroutines to do stuff.
}
}

// Unlock unlocks sl, unlike [Mutex.Unlock](http://golang.org/pkg/sync/#Mutex.Unlock), there's no harm calling it on an unlocked SpinLock.
// Unlock unlocks sl, unlike [Mutex.Unlock](http://golang.org/pkg/sync/#Mutex.Unlock),
// there's no harm calling it on an unlocked SpinLock
func (sl *SpinLock) Unlock() {
atomic.StoreUint32((*uint32)(sl), 0)
atomic.StoreUint32(&sl.l, 0)
}

// TryLock will try to lock sl and return whether it succeed or not without blocking.
func (sl *SpinLock) TryLock() bool {
return atomic.CompareAndSwapUint32((*uint32)(sl), 0, 1)
return atomic.CompareAndSwapUint32(&sl.l, 0, 1)
}

func (sl *SpinLock) String() string {
return state[*sl]
return state[sl.l]
}

0 comments on commit 594f507

Please sign in to comment.