Thuta Learning
Go
AdvancedProgrammingBeginner

Goroutines (Concurrency)

GoLesson 1935 min

What you'll walk away with

  • Explain what a go statement does immediately and what it leaves for later
  • Know that the program ends when main() returns, and wait for goroutines with a WaitGroup
  • Collect results in a predictable order by letting each goroutine write only its own index
  • Recognise why print order cannot be trusted and what a data race on shared state looks like

Explain it simply

Goroutines in plain language

A goroutine is a lightweight line of work managed by the Go runtime. Put the word go in front of a function call and that function starts running in the background while the caller moves on without waiting. It shines for work that spends most of its time waiting, such as sending many requests or processing many files at once.

Think of a restaurant kitchen. If the chef finishes one dish before starting the next, guests wait a long time. Hand each dish to a helper and they all cook at once, but the chef still has to wait until every plate is ready before sending the order out. That waiting part is the heart of this lesson.

Problem → Why → Solution

The problem: goroutines that silently vanish

You add go to make three jobs finish faster. The program runs without an error and exits without printing anything. Sometimes one or two lines appear, and the order changes when you run it again. Many developers 'fix' this by adding time.Sleep, which breaks again on the day the machine is slow.

lost.go
package main

import "fmt"

func main() {
	for i := 1; i <= 3; i++ {
		go fmt.Println("job", i)
	}
	// main returns here: the program exits, and the goroutines
	// usually never get the chance to print anything
}

Why this happens

A go statement only starts the goroutine; it does not wait for it to finish. When main() returns, the whole program stops and any goroutines still running are cut off without warning. On top of that, the scheduler decides when each goroutine runs, so print order is not guaranteed either. The fix is not a sleep but synchronization that signals completion for certain.

Core concept: the life of a goroutine

Writing go f(x) does two things. First, f and its argument x are evaluated right away, in the current goroutine. Second, f is scheduled to run in a new goroutine and the caller continues with the next line immediately. Any return values of f are thrown away, so a goroutine that wants to hand back a result needs another route, such as a slot it owns or a channel.

Goroutines are not OS threads. The Go runtime's scheduler multiplexes many goroutines onto a few OS threads, and when one goroutine waits on I/O or a sleep, another one runs in its place. A goroutine starts with a small stack of a few kilobytes that grows on demand, so starting thousands of them is normal. Concurrency is about structuring work so that it can overlap; running truly simultaneously on several cores (parallelism) is one possible result of that.

main() is the program's main goroutine. When it returns, the program ends, no matter how far the other goroutines have got. So for every goroutine you start you must answer the question 'who waits for it?'. The simplest answer is sync.WaitGroup: wg.Add(1) increments a counter before the go statement, defer wg.Done() decrements it inside the goroutine, and wg.Wait() blocks until the counter reaches zero.

The scheduler gives no guarantee about the order in which goroutines run, so never use their finishing order as your output order. When you need results in order, give each goroutine its own slot such as results[i]: different goroutines writing different elements of a slice is safe. Several goroutines modifying one variable, with counter++ or append, is a data race and can lose results.

Loop variables and the Go version

Since Go 1.22 every iteration of a for loop gets fresh copies of i and page, so a closure inside the goroutine sees its own iteration's values. This depends on the go line in go.mod: modules that say go 1.21 or lower share one variable across all iterations and must pass the value as an argument instead.

Start, wait, collect
  1. Register the work with wg.Add(1)
  2. Start it with go func() { ... }()
  3. Write only results[i]; defer wg.Done()
  4. Wait for all with wg.Wait()
  5. Read results only after Wait

At every line that starts a goroutine, ask 'who waits for this?'. If there is no answer, you have a leak or lost work.

General pattern

go
var wg sync.WaitGroup
results := make([]Result, len(inputs))

for i, in := range inputs {
	wg.Add(1)
	go func() {
		defer wg.Done()
		results[i] = work(in)
	}()
}
wg.Wait() // results is complete and safe to read

Start one goroutine per input, increment the counter before starting it and defer Done inside it. Because each goroutine writes only its own index, no lock is needed and the results stay in input order.

Worked example: fetching four pages at once

fetch fakes a network call that takes 100ms. Called one after another, four calls would take about 400ms, but four goroutines wait at the same time, so the whole run takes roughly 100ms. Results are stored by index rather than in finishing order, so every run prints the same output. The last line checks only whether the run took under 300ms instead of printing an exact time.

fetch.go
package main

import (
	"fmt"
	"strings"
	"sync"
	"time"
)

// fetch stands in for a slow network call.
func fetch(page string) string {
	time.Sleep(100 * time.Millisecond)
	return strings.ToUpper(page)
}

func main() {
	pages := []string{"home", "about", "pricing", "blog"}
	results := make([]string, len(pages)) // one slot per goroutine

	start := time.Now()
	var wg sync.WaitGroup
	for i, page := range pages {
		wg.Add(1) // count the goroutine before starting it
		go func() {
			defer wg.Done()           // signal "finished", even on panic
			results[i] = fetch(page) // each goroutine owns results[i]
		}()
	}
	wg.Wait() // block until all four have called Done

	for i, r := range results {
		fmt.Println(i, r)
	}
	elapsed := time.Since(start)
	fmt.Println("finished in under 300ms:", elapsed < 300*time.Millisecond)
}

Code breakdown

  1. One slot per goroutineresults := make([]string, len(pages)) // one slot per goroutine

    The slice is created at full length before any goroutine starts. The goroutines never append; each writes only its own index, so they never touch each other's data.

  2. Count before startingwg.Add(1) // count the goroutine before starting it

    Add must be called before the go statement. Called inside the goroutine, Wait could run before the counter goes up and return without waiting for anything.

  3. Always signal Donedefer wg.Done() // signal "finished", even on panic

    defer guarantees Done runs however the function exits. Forget Done and Wait never returns.

  4. Write your own indexresults[i] = fetch(page) // each goroutine owns results[i]

    Since Go 1.22, i and page are separate for every iteration, so the closure can use them directly. Each goroutine writes a different index, so no lock is needed.

  5. Read after Waitwg.Wait() // block until all four have called Done

    Only after Wait returns is the main goroutine guaranteed to see every write the goroutines made, so results is read only after this line.

You should see
0 HOME
1 ABOUT
2 PRICING
3 BLOG
finished in under 300ms: true
The main goroutine and its workers
  1. main calls wg.Add(1) and starts a goroutine
  2. Four goroutines wait on fetch at the same time
  3. Each writes results[i] and calls Done
  4. Wait returns once the counter is zero
  5. main prints results in index order

With Wait

every result is printed, in index order

Without Wait

main returns early and the work is lost

Arguments are evaluated immediately

The arguments of a go statement are computed when the go line runs, not when the new goroutine gets scheduled. In the program below msg changes after the goroutine starts, yet the goroutine sees the copy it already received, "first". A closure captures the variable itself and gets no such protection.

args.go
package main

import (
	"fmt"
	"sync"
)

func main() {
	var wg sync.WaitGroup
	msg := "first"

	wg.Add(1)
	go func(m string) { // m is a copy made right now
		defer wg.Done()
		fmt.Println("argument:", m)
	}(msg)

	msg = "second"
	wg.Wait()
	fmt.Println("variable now:", msg)
}

The output is argument: first followed by variable now: second. The second line always comes last because of wg.Wait(): main cannot continue until the goroutine has printed and called Done.

What is safe and what is a data race

A data race happens when two goroutines access the same memory location without synchronization and at least one of them writes. The behaviour of a racy program is unpredictable: it can pass tests and still lose values under production load. go run -race or go test -race reports the races that actually happen during the run.

PatternResult
results[i] = v (each goroutine a different i)safe: different memory locations
results = append(results, v)data race: all share one slice header
total++ from many goroutinesdata race: increments can be lost
reading results after Waitsafe: Wait makes every write visible

time.Sleep is not synchronization

Sleeping in main because the goroutines 'should be done by now' is a guess. On a slow machine work is lost; on a fast one time is wasted. Use a real signal such as a WaitGroup, a channel or a mutex.

In real projects

Goroutines in real projects

Go's net/http server handles each incoming connection in its own goroutine, so one slow handler never blocks the other requests. In your own code, you start goroutines on purpose where the cost is waiting time rather than CPU time.

  • Fan-out requests: a product page calls the price, stock and review services at the same time and waits only as long as the slowest one.
  • Batch processing: hundreds of uploaded images are resized in goroutines and the results are collected by index; limiting how many run at once comes in the worker-pool lesson.
  • Background tasks: a server runs one goroutine that refreshes a cache periodically and stops it through a context during shutdown.

Common mistakes

Common mistakes with goroutines

Calling wg.Add inside the goroutine

With go func() { wg.Add(1); defer wg.Done(); ... }(), main may reach wg.Wait() before any goroutine has called Add, see a zero counter and return at once. Always call Add before the go statement; when you know the count you can also call wg.Add(len(items)) once before the loop.

Appending to a shared slice

When many goroutines run results = append(results, r) at once, items can be lost or duplicated, and the -race flag reports the race. If you know the number of items, pre-size the slice and write by index; if not, send results on a channel and let a single goroutine append them.

Treating output order as a guarantee

Printing directly from goroutines, seeing the right order on your laptop and then asserting that order in a test produces random CI failures. Collect the results, order them by index or by sorting, and only then print.

Best practices

Best practices

  • Give every goroutine an owner that waits for it: a WaitGroup, a channel or a context.
  • Hide concurrency inside a function: callers should call an ordinary function and get finished results back.
  • Run go test -race in CI as a matter of routine.
  • When the number of inputs is unbounded, bound the number of goroutines too (a worker pool).

Mini challenge

Mini challenge: counting words in documents

Write countWords. It counts each document in its own goroutine and returns the counts as a slice in the same order as docs. main prints each document's count and the total.

  • Start one goroutine per document
  • Wait with sync.WaitGroup, never with time.Sleep
  • Each goroutine writes only counts[i] (no append)
  • An empty document counts as 0 words
wordcount.go
package main

import (
	"fmt"
	"strings"
	"sync"
)

type Doc struct {
	Name string
	Text string
}

// countWords returns one count per doc, in the same order as docs.
func countWords(docs []Doc) []int {
	// TODO: make a counts slice with one slot per doc
	// TODO: declare a sync.WaitGroup
	// TODO: for each doc: Add, start a goroutine, defer Done,
	//       store len(strings.Fields(text)) in its own slot
	// TODO: Wait, then return counts
	return nil
}

func main() {
	docs := []Doc{
		{"intro.md", "Go makes concurrency cheap"},
		{"empty.md", ""},
		{"notes.md", "goroutines need an owner and a way to finish"},
	}
	// TODO: call countWords, print each name with its count, then the total
	_ = docs
}

Expected: Every run prints intro.md 4 words, empty.md 0 words, notes.md 9 words and total: 13, always in that order.

Show hint

strings.Fields splits on whitespace and returns an empty slice for empty text, so its len is 0. On Go 1.22 and later the loop variables i and d can be used directly inside the closure.

Show solution
wordcount.go
package main

import (
	"fmt"
	"strings"
	"sync"
)

type Doc struct {
	Name string
	Text string
}

// countWords counts every doc in its own goroutine and returns the
// counts in the same order as docs.
func countWords(docs []Doc) []int {
	counts := make([]int, len(docs))
	var wg sync.WaitGroup
	for i, d := range docs {
		wg.Add(1)
		go func() {
			defer wg.Done()
			counts[i] = len(strings.Fields(d.Text))
		}()
	}
	wg.Wait()
	return counts
}

func main() {
	docs := []Doc{
		{"intro.md", "Go makes concurrency cheap"},
		{"empty.md", ""},
		{"notes.md", "goroutines need an owner and a way to finish"},
	}
	counts := countWords(docs)
	total := 0
	for i, d := range docs {
		fmt.Printf("%-9s %d words\n", d.Name, counts[i])
		total += counts[i]
	}
	fmt.Println("total:", total)
}

Quick quiz 1 / 3

main() runs go fmt.Println("hi") and then returns immediately. What happens?

Quick quiz 2 / 3

Where should wg.Add(1) be called when waiting for goroutines?

Quick quiz 3 / 3

Five goroutines run results = append(results, r) on one shared slice, then main calls wg.Wait(). What is wrong?

What to remember

  • go f(x) evaluates its arguments immediately, runs f in a new goroutine and lets the caller continue without waiting.
  • The program ends when main() returns, so every goroutine needs someone who waits for it.
  • WaitGroup: Add before go, defer Done inside, then Wait.
  • Goroutine scheduling order is not guaranteed; collect results by index before printing.
  • Modifying shared variables concurrently without a lock is a data race, and the -race flag finds it.

A Tour of Go — Go

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Goroutines (Concurrency) | Thuta Learning