Using sync.Mutex
Mutex is an abbreviation for mutual exclusion; the Mutex variables are mainly used for thread synchronization and for protecting shared data when multiple writes can occur at the same time. A mutex works like a buffered channel of capacity 1 that allows at most one goroutine to access a shared variable at a time. This means that there is no way for two or more goroutines to try to update that variable simultaneously. Although this is a perfectly valid technique, the general Go community prefers to use the monitor goroutine technique presented in the previous section.
In order to use sync.Mutex, you will have to declare a sync.Mutex variable first. You can lock that variable using the Lock method and release it using the ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access