Skip to content

Instantly share code, notes, and snippets.

@pavelpatrin
Last active January 26, 2021 19:47
Show Gist options
  • Save pavelpatrin/3f35b5ed7d6f77105653641a30e1f3ac to your computer and use it in GitHub Desktop.
Save pavelpatrin/3f35b5ed7d6f77105653641a30e1f3ac to your computer and use it in GitHub Desktop.
Example of atomic store
package main
import (
"fmt"
"math/bits"
"runtime"
"sync/atomic"
"time"
)
var value uint64
func main() {
fmt.Println(runtime.NumCPU())
// go func() { for{value = 0b0000000000000000000000000000000000000000000000000000000000000001} }()
// go func() { for{value = 0b00000000000000000000000000000000000000000000000000000001} }()
// go func() { for{value = 0b000000000000000000000000000000000000000000000001} }()
// go func() { for{value = 0b0000000000000000000000000000000000000001} }()
// go func() { for{value = 0b00000000000000000000000000000001} }()
// go func() { for{value = 0b000000000000000000000001} }()
// go func() { for{value = 0b000000000000001} }()
// go func() { for{value = 0b0000001} }()
go func() { for { atomic.StoreUint64(&value, 0b0000000000000000000000000000000000000000000000000000000000000001) } }()
go func() { for { atomic.StoreUint64(&value, 0b00000000000000000000000000000000000000000000000000000001) } }()
go func() { for { atomic.StoreUint64(&value, 0b000000000000000000000000000000000000000000000001) } }()
go func() { for { atomic.StoreUint64(&value, 0b0000000000000000000000000000000000000001) } }()
go func() { for { atomic.StoreUint64(&value, 0b00000000000000000000000000000001) } }()
go func() { for { atomic.StoreUint64(&value, 0b000000000000000000000001) } }()
go func() { for { atomic.StoreUint64(&value, 0b000000000000001) } }()
go func() { for { atomic.StoreUint64(&value, 0b0000001) } }()
time.Sleep(time.Second)
for {
local := value
if bits.OnesCount64(local) != 1 {
panic(fmt.Sprintf("Caught: %v", local))
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment