Skip to content

Commit

Permalink
added atomicflag and coverted spinlock to use it.
Browse files Browse the repository at this point in the history
  • Loading branch information
OneOfOne committed Sep 6, 2014
1 parent 594f507 commit 2864d80
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 13 deletions.
26 changes: 26 additions & 0 deletions sync/atomicflag.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package sync

import "sync/atomic"

type AtomicFlag struct {
v uint32
}

func (a *AtomicFlag) Set() bool {
return atomic.CompareAndSwapUint32(&a.v, 0, 1)
}

func (a *AtomicFlag) Clear() bool {
return atomic.CompareAndSwapUint32(&a.v, 1, 0)
}

func (a *AtomicFlag) IsSet() bool {
return atomic.LoadUint32(&a.v) == 1
}

func (a *AtomicFlag) String() string {
if a.IsSet() {
return "true"
}
return "false"
}
22 changes: 10 additions & 12 deletions sync/spinlock.go
Original file line number Diff line number Diff line change
@@ -1,35 +1,33 @@
package spinlock
package sync

import (
"runtime"
"sync/atomic"
)

var state = [2]string{"Unlocked", "Locked"}
import "runtime"

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

// Lock locks sl. If the lock is already in use, the caller blocks until Unlock is called
func (sl *SpinLock) Lock() {
for !atomic.CompareAndSwapUint32(&sl.l, 0, 1) {
for !sl.v.Set() {
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
func (sl *SpinLock) Unlock() {
atomic.StoreUint32(&sl.l, 0)
sl.v.Clear()
}

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

func (sl *SpinLock) String() string {
return state[sl.l]
if sl.v.IsSet() {
return "Locked"
}
return "Unlocked"
}
2 changes: 1 addition & 1 deletion sync/spinlock_test.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package spinlock
package sync

import (
"sync"
Expand Down

0 comments on commit 2864d80

Please sign in to comment.