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.

GoData Integrity

Code

gosnippet
46 lines
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

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:`.