Go Atomic Synchronization
Synchronization Primitives with sync/atomic
Welcome to the next step in our exploration of concurrency in Go. Building on your foundation in Go concurrency from the prerequisite course, where you learned about goroutines, race conditions, and basic synchronization, we now venture into synchronization primitives, with a spotlight on the sync/atomic package. synchronization is at the heart of concurrent programming, ensuring that goroutines interact with shared data predictably and safely. This lesson will equip you with the tools to manage these interactions effectively.
What You'll Learn
In this lesson, we will dissect the synchronization capabilities offered by the sync/atomic package:
- Understanding
sync/atomic: We will explore what thesync/atomicpackage ensures, why it is essential for concurrency, and how it differs from regular variables. - Lock-free programming: You'll learn about the benefits and limitations of lock-free programming, harnessing the power of atomic operations to improve performance in multi-goroutine applications.
Introduction to sync/atomic
Before moving to the code example, let's understand what the sync/atomic package is and why it is crucial for concurrent programming.
The sync/atomic package in Go provides atomic operations on shared data. It ensures that when multiple goroutines access the same data concurrently, the operations are performed atomically without interference from other goroutines. This means that if goroutine 1 is modifying a shared variable, goroutine 2 will not read or write to it until goroutine 1 has completed its atomic operation.
To illustrate this, let's examine a piece of code that emphasizes these concepts:
Let's break down the code:
- We define a
SynchronizedCounterstruct with a single fieldcountof typeint32. - The
incrementmethod increments the counter atomically using theatomic.AddInt32function.- The
atomic.AddInt32function atomically increments the counter by1. It takes a pointer to the variable and the value to add. Note that theatomic.AddInt32function is an atomic operation, ensuring that, in the middle of the operation, no other goroutine can access the shared data. - The function returns the new value after the addition, although we do not use it in this example.
- The
- The
getCountmethod reads the counter value atomically using theatomic.LoadInt32function.- The
atomic.LoadInt32function atomically reads the counter value and returns it, ensuring no other goroutine can modify the value during the read.
- The
- In the
mainfunction, we create aSynchronizedCounterand async.WaitGroupto coordinate the goroutines. - We launch two goroutines that each increment the counter
1000times. - We use
wg.Wait()to ensure both goroutines complete before reading the final count.
You might ask: why not simply use a regular int32 and the increment operation count++? The answer lies in the atomicity of the operation.
If count were accessed without atomic operations, the increment count++ would not be atomic. Instead, it would consist of three distinct operations:
- Load: Reading the current value from memory.
- Increment: Adding
1to the value. - Store: Writing the updated value back to memory.
In a multi-goroutine environment, these steps can be interleaved. For instance, if goroutine 1 loads the value as 5 and, before it can write the result (6) back to memory, goroutine 2 also loads the value as 5. Both goroutines will then increment their local copies to 6 and write them back. Consequently, one of the increments is "lost," and the final count becomes 6 instead of 7.
By using atomic.AddInt32, we ensure that this entire read-modify-write sequence is performed as a single, indivisible operation. No other goroutine can see the variable in an intermediate state or interfere until the operation is complete.
The importance of atomic operations becomes evident in scenarios where operations are more complex and involve multiple steps. By using atomic operations, we can ensure that these tasks are performed atomically, without interference from other goroutines.
