ProgramGuru

Introduction to Concurrency

Start with Introduction to Concurrency

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

What you’ll learn

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

Understand the idea

Concurrency means organizing multiple tasks so their progress can overlap. In Go, goroutines run functions independently, while channels and synchronization tools coordinate them.

The example runs two calculations concurrently but gives their results a fixed order when printing. Starting goroutines alone does not guarantee they finish before main exits.

Visualize how it works

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

Visual explanation for concurrencyCoordination makes a concurrent result dependable.Launch workStep 1Compute concurrentlyStep 2Receive resultsStep 3Print sumStep 4Coordination makes a concurrent result dependable.
Coordination makes a concurrent result dependable.

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() {
	results := make(chan int, 2)
	go func() { results <- 2 * 3 }()
	go func() { results <- 4 * 5 }()
	a, b := <-results, <-results
	fmt.Println("Sum:", a+b)
}

Output

Sum: 26

Trace what the program does

Both goroutines send exactly one computed integer. The two receives wait for both results, and addition is order-independent, so Sum: 26 is stable.

Avoid common mistakes

  • A goroutine runs independently; launching one is not the same as waiting for it.
  • The order in which two goroutines finish is not guaranteed.

Try it yourself

Add a third multiplication goroutine and receive a third result before printing the sum.

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

Check your understanding

What makes the final sum safe to print?
Choose one answer. You can try again.

Answer and explanation

Two channel receives wait for both results

Correct. Both goroutines send exactly one computed integer.

What you should remember

You have practiced Introduction to Concurrency 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: Concurrency vs Parallelism →