ProgramGuru

Concurrency Programs

Start with Concurrency Programs

Learn concurrency programs through an executable example, then connect the small demonstration to production code.

What you’ll learn

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

Understand the idea

Concurrency exercises combine independent tasks with coordination. Use a result channel, a WaitGroup or another appropriate synchronization mechanism, and never assume completion order.

The example computes four squares concurrently and uses indexes to reconstruct a deterministic ordered slice.

Visualize how it works

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

Visual explanation for example concurrencyCoordinate completion and preserve stable output.Start workersStep 1Compute concurrentlyStep 2Receive indexed dataStep 3Restore orderStep 4Coordinate completion and preserve stable output.
Coordinate completion and preserve stable output.

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"

type Result struct{ Index, Value int }

func main() {
	results := make(chan Result, 4)
	for i := 1; i <= 4; i++ {
		go func(n int) { results <- Result{n - 1, n * n} }(i)
	}
	ordered := make([]int, 4)
	for range ordered {
		r := <-results
		ordered[r.Index] = r.Value
	}
	fmt.Println("Squares:", ordered)
}

Output

Squares: [1 4 9 16]

Trace what the program does

Workers may finish in any order. Every message carries its original index, so the receiver reconstructs [1 4 9 16] and prints a predictable sequence.

Avoid common mistakes

  • Starting goroutines is not the same as joining them.
  • Channel communication does not make every other shared variable race-free.

Try it yourself

Compute cubes instead and add a fifth worker; then test with go run -race.

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

Check your understanding

Why store results by their indexes?
Choose one answer. You can try again.

Answer and explanation

To restore input order despite concurrent execution

Correct. Workers may finish in any order.

What you should remember

You have practiced Concurrency Programs 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: Command-Line Calculator →