Last active
September 24, 2015 20:51
-
-
Save theevocater/f2fda92aa04dea4d7142 to your computer and use it in GitHub Desktop.
Atomic bool in go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"sync/atomic" | |
) | |
type AtomicBool struct { | |
value *int32 | |
} | |
func bToI(b bool) int32 { | |
if b { | |
return 1 | |
} | |
return 0 | |
} | |
func iToB(i int32) bool { | |
if i == 1 { | |
return true | |
} | |
return false | |
} | |
func (b *AtomicBool) Get() bool { | |
return iToB(atomic.LoadInt32(b.value)) | |
} | |
func (b *AtomicBool) Set(v bool) { | |
atomic.StoreInt32(b.value, bToI(v)) | |
} | |
func (b *AtomicBool) CompareAndSwap(old, new bool) bool { | |
return atomic.CompareAndSwapInt32(b.value, bToI(old), bToI(new)) | |
} | |
func (b *AtomicBool) Swap(new bool) bool { | |
return iToB(atomic.SwapInt32(b.value, bToI(new))) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment