Go by Example: Mutexes
Go by Example : Mutexes
In the previous example we saw how to manage simple counter state using atomic operations . For more complex state we can use a mutex to safely access data across multiple goroutines. | |
| |
| |
Container holds a map of counters; since we want to
update it concurrently from multiple goroutines, we
add a
|
|
Lock the mutex before accessing
|
|
| |
Note that the zero value of a mutex is usable as-is, so no initialization is required here. |
|
| |
| |
This function increments a named counter in a loop. |
|
Run several goroutines concurrently; note
that they all access the same
|
|
Wait for the goroutines to finish |
|
Running the program shows that the counters updated as expected. |
|
Next we’ll look at implementing this same state management task using only goroutines and channels. |
Next example: Stateful Goroutines .