ProgramGuru

Race Conditions

Start with Race Conditions

In this lesson, explore race conditions through one small Go program, and connect its output to the language rules behind it.

What you’ll learn

  • Explain the main purpose of race conditions.
  • Read and run the complete Go example in this lesson.
  • Apply the concept and recognize common mistakes.

Understand the idea

A data race occurs when two goroutines access the same memory concurrently, at least one writes, and the accesses are not properly synchronized. Such a program has invalid assumptions even if its output sometimes looks right.

The example avoids a race by sending updates to one owner goroutine through a channel; no worker writes the shared counter directly.

Visualize how it works

Follow this diagram before executing the example. Check where a value or decision changes what runs next.

Visual explanation for race conditionsOwnership can eliminate shared writes.Three sendersStep 1Channel updatesStep 2Single owner changes sumStep 3Print totalStep 4Ownership can eliminate shared writes.
Ownership can eliminate shared writes.

Run a complete Go example

This example is a complete program. Save it as main.go or paste it into the Go Playground.

Go code

package main

import "fmt"

func main() {
	updates := make(chan int, 3)
	for i := 0; i < 3; i++ {
		go func() { updates <- 1 }()
	}
	sum := 0
	for i := 0; i < 3; i++ {
		sum += <-updates
	}
	fmt.Println("Total:", sum)
}

Output

Total: 3

Trace what the program does

Each goroutine sends 1. Only main changes sum, and each receive ensures one update arrived. The total is 3.

Avoid common mistakes

  • Running code repeatedly without errors does not prove race freedom.
  • Protect read and write operations, not only writes.

Try it yourself

Compare this owner-loop approach with protecting sum using a mutex.

Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.

Check your understanding

Which pattern avoids a data race here?
Choose one answer. You can try again.

Answer and explanation

Only one goroutine updates sum

Correct. Each goroutine sends 1.

What you should remember

You have practiced Race Conditions in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.

Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: Race Detection →