The atomic package
An atomic operation is an operation that is completed in a single step relative to other threads or, in this case, to other goroutines. This means that an atomic operation cannot be interrupted in the middle of it.
The Go standard library offers the atomic package, which, in some cases, can help you to avoid using a mutex. However, mutexes are more versatile than atomic operations. Using the atomic package, you can have atomic counters accessed by multiple goroutines without synchronization issues and race conditions.
Notice that, if you have an atomic variable, all reading and writing must be done using the atomic functions provided by the atomic package. The use of the atomic package will be illustrated with the atom.go ...
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