Permalink
Browse files

added two very basic spin lock implementations

  • Loading branch information...
0 parents commit bfb8496478fec7c83eec94c3a7e4be5409788d8b @tux21b committed May 12, 2012
Showing with 97 additions and 0 deletions.
  1. +6 −0 README
  2. +43 −0 lock.go
  3. +48 −0 lock_test.go
6 README
@@ -0,0 +1,6 @@
+The goco package just contains some experiments with some concurrent
+datastructures implemented in Go.
+
+Run the benchmarks with:
+
+ go test -bench="." -benchtime=5 -cpu=1,2,4,8,16
43 lock.go
@@ -0,0 +1,43 @@
+// Copyright (c) 2012 by Christoph Hack <christoph@tux21b.org>
+// All rights reserved. Distributed under the Simplified BSD License.
+
+package goco
+
+import "sync/atomic"
+
+type Lock interface {
+ Lock()
+ Unlock()
+}
+
+type TASLock struct {
+ state int32
+}
+
+func (l *TASLock) Lock() {
+ for !atomic.CompareAndSwapInt32(&l.state, 0, 1) {
+ }
+}
+
+func (l *TASLock) Unlock() {
+ atomic.StoreInt32(&l.state, 0)
+}
+
+type TTASLock struct {
+ state int32
+}
+
+func (l *TTASLock) Lock() {
+ for {
+ for atomic.LoadInt32(&l.state) != 0 {
+ }
+
+ if atomic.CompareAndSwapInt32(&l.state, 0, 1) {
+ return
+ }
+ }
+}
+
+func (l *TTASLock) Unlock() {
+ atomic.StoreInt32(&l.state, 0)
+}
48 lock_test.go
@@ -0,0 +1,48 @@
+// Copyright (c) 2012 by Christoph Hack <christoph@tux21b.org>
+// All rights reserved. Distributed under the Simplified BSD License.
+
+package goco
+
+import (
+ "runtime"
+ "sync"
+ "testing"
+)
+
+func BenchmarkTASLock(b *testing.B) {
+ procs := runtime.GOMAXPROCS(-1)
+ n := b.N / procs
+ lock := new(TASLock)
+ wg := new(sync.WaitGroup)
+ wg.Add(procs)
+ for proc := 0; proc < procs; proc++ {
+ go func() {
+ runtime.LockOSThread()
+ for i := 0; i < n; i++ {
+ lock.Lock()
+ lock.Unlock()
+ }
+ wg.Done()
+ }()
+ }
+ wg.Wait()
+}
+
+func BenchmarkTTASLock(b *testing.B) {
+ procs := runtime.GOMAXPROCS(-1)
+ n := b.N / procs
+ lock := new(TTASLock)
+ wg := new(sync.WaitGroup)
+ wg.Add(procs)
+ for proc := 0; proc < procs; proc++ {
+ go func() {
+ runtime.LockOSThread()
+ for i := 0; i < n; i++ {
+ lock.Lock()
+ lock.Unlock()
+ }
+ wg.Done()
+ }()
+ }
+ wg.Wait()
+}

0 comments on commit bfb8496

Please sign in to comment.