Skip to content

Instantly share code, notes, and snippets.

@theevocater
Last active September 24, 2015 20:51
Show Gist options
  • Save theevocater/f2fda92aa04dea4d7142 to your computer and use it in GitHub Desktop.
Save theevocater/f2fda92aa04dea4d7142 to your computer and use it in GitHub Desktop.
Atomic bool in go
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