Atomic Bool Swap Flag
Use atomic.Bool Swap and CompareAndSwap to flip a shared flag across goroutines without a mutex, watching each returned value.
Code
package main
import (
"fmt"
"sync"
"sync/atomic"
)
func main() {
var flag atomic.Bool
fmt.Println("initial:", flag.Load())
// CompareAndSwap writes only while the expected value still matches
fmt.Println("cas false to true:", flag.CompareAndSwap(false, true))
fmt.Println("cas false again:", flag.CompareAndSwap(false, true))
flag.Store(false)
// Swap stores a new value and returns the previous one
switches := 0
for i := 0; i < 5; i++ {
previous := flag.Swap(i%2 == 0)
if previous {
switches++
}
}
fmt.Println("after swaps:", flag.Load())
fmt.Println("previous true count:", switches)
var wg sync.WaitGroup
for i := 0; i < 8; i++ {
wg.Add(1)
go func() {
defer wg.Done()
// Store and Load are individually atomic, not a combined toggle
flag.Store(!flag.Load())
}()
}
wg.Wait()
fmt.Println("final observed:", flag.Load())
}The structure at work
The code’s whole job belongs to the function main.
A single loop drives the file — for i := 0; i < 5; i++. The task is handed to a goroutine and runs concurrently. The cleanup call is deferred to function exit — success, early return, and panic all covered.
Points of care
- The toolchain by itself is enough — dependency resolution never runs.
Using it
The main signature reads func main()
Running the file prints labeled results such as initial:, cas false to true:, cas false again: — each operation’s effect is visible in the output.
Key statements
var wg sync.WaitGroup
defer wg.Done()
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.
FAQ
- What does Atomic Bool Swap Flag print when run?
- No setup needed: run the file and look for labeled lines like `initial:`, `cas false to true:`, `cas false again:` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.