Atomic Compare And Swap Retry Loop
Coordinate lock-free handoff with atomic CompareAndSwap, where one goroutine wins the swap and concurrent counters retry until their write lands.
Code
package main
import (
"fmt"
"sync"
"sync/atomic"
)
func main() {
var (
tickets atomic.Int64
wg sync.WaitGroup
)
// CompareAndSwap 只允许一个赢家:把 0 换成 1 的那个 goroutine 当选
for worker := 1; worker <= 4; worker++ {
wg.Add(1)
go func(id int) {
defer wg.Done()
if tickets.CompareAndSwap(0, 1) {
fmt.Println("worker", id, "elected leader")
return
}
fmt.Println("worker", id, "lost the race")
}(worker)
}
wg.Wait()
fmt.Println("leader elected:", tickets.Load() == 1)
// CAS 循环:并发累加时重试到成功为止
var counter atomic.Int64
for i := 0; i < 2; i++ {
wg.Add(1)
go func() {
defer wg.Done()
for {
current := counter.Load()
if counter.CompareAndSwap(current, current+10) {
break
}
}
}()
}
wg.Wait()
fmt.Println("counter:", counter.Load())
}Where the work happens
Atomic Compare And Swap Retry Loop keeps everything in the function main.
A single loop drives the file — for worker := 1; worker <= 4; worker++. 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.
What to watch for
- Nothing external is touched; behavior comes from the standard library alone.
Using it
Entry signature: func main()
Look for the worker, leader elected:, counter: prefixes when the file runs; they tie each line to its step.
Key statements
go func(id int) {
defer wg.Done()
if tickets.CompareAndSwap(0, 1) {
fmt.Println("worker", id, "elected leader")
return
}
fmt.Println("worker", id, "lost the race")
}(worker)
wg sync.WaitGroup
Interactive Tools for This Topic
HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.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.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.Text Diff ComparisonCompare two text blocks line by line and visualize the differences with added, removed, and unchanged lines highlighted. Useful for reviewing changes and patches.
FAQ
- What does Atomic Compare And Swap Retry Loop print when run?
- The script runs standalone; its 3 labeled outputs include `worker`, `leader elected:`, `counter:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.