Atomic Counter Claims Work Indices

Distribute dynamic work with one atomic counter: each worker claims the next index, writes its own slot, and exits when exhausted.

GoResilience

Code

gosnippet
37 lines
package main

import (
	"fmt"
	"sync"
	"sync/atomic"
)

func main() {
	const jobs = 6
	var next atomic.Uint64
	var wg sync.WaitGroup

	// dynamic work distribution: each worker claims one of the work indices
	// from the atomic counter, and writes only its own slice slot
	results := make([]string, jobs)
	for worker := 1; worker <= 3; worker++ {
		wg.Add(1)
		go func(id int) {
			defer wg.Done()
			for {
				index := int(next.Add(1)) - 1
				if index >= jobs {
					return
				}
				results[index] = fmt.Sprintf("worker %d did job %d", id, index)
			}
		}(worker)
	}
	wg.Wait()

	// which worker ran which job varies between runs; every job ran exactly once
	for _, line := range results {
		fmt.Println(line)
	}
	fmt.Println("claimed:", next.Load(), "for", jobs, "jobs")
}

Walkthrough of the file

Atomic Counter Claims Work Indices reduces to the function main.

The file repeats itself only inside for worker := 1; worker <= 3; worker++. Work is dispatched on a goroutine. defer inverts the usual order — register now, run at return — which is why cleanup cannot be skipped.

What to watch for

  • No third-party code is loaded at any point while this runs.

Applying it

Output lines are prefixed (claimed:), keeping every printed line tied to the step that produced it.

Statements that matter

for _, line := range results {
	fmt.Println(line)
}
go func(id int) {
	defer wg.Done()
	for {
		index := int(next.Add(1)) - 1
		if index >= jobs {
			return
		}
		results[index] = fmt.Sprintf("worker %d did job %d", id, index)
	}
}(worker)
results := make([]string, jobs)

Interactive Tools for This Topic

FAQ

What does Atomic Counter Claims Work Indices print when run?
Run it as a complete program — the output lines carry labels such as `claimed:`.