Practical uses of atomics
Here are a few examples of using atomics. These are simple race-free uses of atomics in different scenarios.
Counters
Atomics can be used as efficient concurrency-safe counters. The following program creates many goroutines, each of which will add 1
to the shared counter. Another goroutine loops until the counter reaches 10000
. Because of the use of atomics here, this program is race-free, and it will always terminate by eventually printing 10000
:
var count int64 func main() { for i := 0; i < 10000; i++ { go func() { atomic.AddInt64(&count, 1) }() } for { &...