Skip to content
Codewilds

Lesson 32 of 38 · Concurrency

Goroutines in Go: Lightweight Concurrency

medium20 XP4 min read

So far, every program you have written did one thing at a time: each statement waited for the one before it. Real programs juggle many independent jobs — serving web requests, downloading files, crunching numbers — and doing them one by one wastes time. Go was built for this: starting a concurrent task takes a single keyword.

Welcome to the last island of the Gopher Isles, where hundreds of gophers work side by side. Your job is to coordinate them.

The go keyword

Put go in front of a function call and Go runs that call in a new goroutine — a function that executes concurrently with the rest of your program. The caller doesn't wait; it moves on to its next statement immediately:

go saveScore(player) // runs in the background
go func() {          // anonymous functions work too
	fmt.Println("working...")
}()

Goroutines are not operating-system threads. The Go runtime gives each one a tiny stack of a few kilobytes that grows when needed, and schedules thousands — even millions — of them onto a handful of threads. Starting one is cheap, so Go programs use them freely: a Go web server typically handles every request in its own goroutine.

main does not wait

A Go program ends as soon as main returns, no matter how many goroutines are still running:

package main

import "fmt"

func main() {
	go fmt.Println("hello from a goroutine")
	fmt.Println("main is done")
}
main is done

Usually the goroutine never even gets a chance to print. Adding a time.Sleep to main might "fix" it on your machine and break it on a slower one. You need a real way to wait.

Waiting with sync.WaitGroup

A sync.WaitGroup counts unfinished goroutines:

  • wg.Add(1) increases the counter — call it before starting the goroutine,
  • wg.Done() decreases it — call it with defer at the top of the goroutine, so it runs however the goroutine ends,
  • wg.Wait() blocks until the counter is back to zero.
package main

import (
	"fmt"
	"sync"
)

func main() {
	words := []string{"go", "gopher", "goroutine"}
	lengths := make([]int, len(words))

	var wg sync.WaitGroup
	for i, w := range words {
		wg.Add(1)
		go func() {
			defer wg.Done()
			lengths[i] = len(w)
		}()
	}
	wg.Wait() // every goroutine has finished here

	fmt.Println(lengths)
}
[2 6 9]

The three goroutines may run in any order, yet the output never changes. Each goroutine writes only to its own index, and main reads the slice only after Wait returns. Different elements of a slice are different variables, so no two goroutines ever touch the same memory — no locking needed.

Passing data into goroutines

The goroutines above use the loop variables i and w directly. That's safe since Go 1.22, because every loop iteration gets fresh variables. You will still often see values passed as arguments — to a function literal, go func(i int, w string) { … }(i, w), or to a named function:

// measure stores the length of w in lengths[i].
func measure(i int, w string, lengths []int, wg *sync.WaitGroup) {
	defer wg.Done()
	lengths[i] = len(w)
}

// inside main:
for i, w := range words {
	wg.Add(1)
	go measure(i, w, lengths, &wg)
}

The arguments are evaluated when the go statement runs, so each goroutine gets its own copies. Note the *sync.WaitGroup parameter: the goroutine must share the caller's WaitGroup, not work on a copy.

Concurrency is not parallelism

Concurrency is about structure: a program built from independent tasks whose lifetimes overlap. Parallelism is about execution: several tasks running at the same instant on different CPU cores. You write concurrent code; the Go runtime runs it in parallel when cores are available. In this browser runtime all goroutines take turns on a single thread — concurrent, but not parallel. Correct Go code works either way, so never rely on goroutines running in a particular order.

Common mistakes

  • Not waiting: if your function returns before wg.Wait(), the results of unfinished goroutines are missing.
  • Calling wg.Add(1) inside the goroutine: Wait can run before the goroutine starts and return too early. Call Add before the go statement.
  • Forgetting wg.Done(): the counter never reaches zero, Wait blocks forever and Go stops with fatal error: all goroutines are asleep - deadlock!.
  • Appending to a shared slice from several goroutines: results = append(results, x) is a data race — two goroutines modifying the same variable at once. Write to distinct indices instead; the next lessons show more tools.

Assignment

Use one goroutine per item and a sync.WaitGroup to wait for all of them. The starter doesn't import sync yet (Go rejects unused imports), so add it to the import list.

  1. ParallelSquares(nums []int) []int returns the square of every number, in the same order as nums, computing each square in its own goroutine. An empty input gives an empty result.
  2. RunAll(tasks []func() int) []int runs every task in its own goroutine, waits for all of them and returns the results in task order: result[i] is the value returned by tasks[i].
  3. CountLetter(words []string, letter rune) int returns how many times letter appears in all the words together. Count each word in its own goroutine, store the per-word counts in a slice and add them up after waiting.
ParallelSquares([]int{1, 2, 3, 4})                       // [1 4 9 16]
RunAll([]func() int{func() int { return 7 }})            // [7]
CountLetter([]string{"banana", "apple", "avocado"}, 'a') // 6

Premium lesson

Unlock the full Learn Go course

  • All 38 lessons, bosses and quizzes — lifetime access
  • One payment of $35, no subscription
  • Finish within 30 days and claim $10.50 (30%) back
Play the 9 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.

Async code and concurrency in other languages

Need a quick reminder? The Go cheat sheet has every topic of Learn Go on one page.

Lesson last updated on .

Write code ↓
Go+20 XP

Lesson 32 is part of the full course. The first 9 lessons are free.

Premium lesson

Unlock the full Learn Go course

  • All 38 lessons, bosses and quizzes — lifetime access
  • One payment of $35, no subscription
  • Finish within 30 days and claim $10.50 (30%) back
Play the 9 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.