Synchronizing Shared Data
Understanding Data Sharing Between Goroutines
Welcome back! Now that you have a good grasp of goroutine lifecycles and basic operations, let's move forward to a critical and exciting part of concurrent programming: data sharing between goroutines. In this lesson, we will explore how goroutines can share data using primitive approaches and understand the importance of synchronizing this access.
What You'll Learn
Data sharing between goroutines, while powerful, can lead to unpredictable behavior if not managed correctly. We will cover:
- Shared variables and risks of unsynchronized access.
- Learn how goroutines can share data through shared variables.
- Understand the risks of unsynchronized access, such as race conditions.
- Introduction to synchronization primitives.
- Explore the basic synchronization primitives like
sync.Mutex. - Understand how these tools prevent race conditions by ensuring that only one goroutine can access the shared resource at a time.
- Explore the basic synchronization primitives like
- Code example: Observing race conditions and fixing them.
- We'll demonstrate a race condition and then fix it using
sync.Mutexand Go'sdeferpattern.
- We'll demonstrate a race condition and then fix it using
Let's start with an example that demonstrates the risks of unsynchronized access to shared variables:
This code might produce different results each time it's run due to race conditions. This is because both goroutines are accessing the shared variable counter without any synchronization. Here is a quick scenario that explains the issue:
- goroutine
1reads the value ofcounter(let's say it's15). - goroutine
2reads the value ofcounter(also15). - goroutine
1incrementscounterby1and writes the new value (16). - goroutine
2incrementscounterby1and writes the new value — also16, instead of17, since it read the value before goroutine1updated it. - The final value of
counteris16, instead of the expected17.
