The atomic Package

Let’s learn to use atomic operations in Go to prevent race conditions.

An atomic operation

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 can’t be interrupted in the middle of it. The Go Standard library offers the atomic package, which, in some simple cases, can help us avoid using a mutex. With the atomic package, we can have atomic counters accessed by multiple goroutines without synchronization issues and without worrying about race conditions. However, mutexes are more versatile than atomic operations.

As illustrated in the code that follows, when using an atomic variable, all reading and writing operations of an atomic variable must be done using the functions provided by the atomic package in order to avoid race conditions.

Coding example

The code in atomic.go is as follows, which is made smaller by hardcoding some values:

Get hands-on with 1400+ tech skills courses.