Go by Example: Atomic Counters
Go by Example : Atomic Counters
The primary mechanism for managing state in Go is
communication over channels. We saw this for example
with
worker pools
. There are a few other
options for managing state though. Here we’ll
look at using the
| |
![]() | |
| |
| |
We’ll use an atomic integer type to represent our (always-positive) counter. | |
A WaitGroup will help us wait for all goroutines to finish their work. | |
We’ll start 50 goroutines that each increment the counter exactly 1000 times. | |
| |
To atomically increment the counter we use
| |
| |
Wait until all the goroutines are done. | |
Here no goroutines are writing to ‘ops’, but using
| |
We expect to get exactly 50,000 operations. Had we
used a non-atomic integer and incremented it with
| |
Next we’ll look at mutexes, another tool for managing state. |
Next example: Mutexes .
