Skip to content

Instantly share code, notes, and snippets.

@mahan
Last active January 7, 2021 16:19
Show Gist options
  • Save mahan/6256149 to your computer and use it in GitHub Desktop.
Save mahan/6256149 to your computer and use it in GitHub Desktop.
Atomic boolean for golang
/* Atomic boolean for golang
A process-atomic boolean that can be used for signaling between goroutines.
Default value = false. (nil structure)
*/
package main
import "sync/atomic"
type TAtomBool struct {flag int32}
func (b *TAtomBool) Set(value bool) {
var i int32 = 0
if value {i = 1}
atomic.StoreInt32(&(b.flag), int32(i))
}
func (b *TAtomBool) Get() bool {
if atomic.LoadInt32(&(b.flag)) != 0 {return true}
return false
}
//Test code
func main() {
b1 := new(TAtomBool)
println(b1.Get())
b1.Set(true)
println(b1.Get())
b2 := &TAtomBool{1}
println(b2.Get())
}
@tevino
Copy link

tevino commented May 25, 2016

@RoanBrand
Copy link

func (b *TAtomBool) Get() bool {
return atomic.LoadInt32(&(b.flag)) != 0
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment