Search⌘ K
AI Features

Solution: Write Code with a Race Condition

Explore how to write Go code that leads to a race condition by running concurrent read and write goroutines on shared data without synchronization. Learn to identify the cause of race errors and why using constructs like WaitGroup is preferable over workarounds such as time.Sleep for managing goroutine completion.

Problem breakdown

Let’s walk through the problem statement step by step. The data race condition occurs when two or more threads race to access and modify the same data.

Here are the steps that solve the challenge:

  1. Create one function that will read the value of the data and one function that will update the value.

  2. Place them inside goroutines to make both of them run concurrently. ...