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 unsigned integer 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. |
|
It’s safe to access |
|
We expect to get exactly 50,000 operations. Had we
used the non-atomic |
|
Next we’ll look at mutexes, another tool for managing state. |
Next example: Mutexes.