IntermediateLesson 8 of 155 min read

Goroutines and Channels: Doing Many Things at Once

Learn goroutines, WaitGroup, unbuffered and buffered channels, range over a channel, select with a timeout and a pipeline, with results checked by a formula and a timing comparison.

In this lesson you will

  • Start goroutines and wait for them
  • Pass values through channels
  • Use select with a timeout
  • Compare concurrent and sequential work

About 28 minutes

Checking forty parcels at once

Mei’s program asks a carrier’s website for the status of each parcel, and every request takes a fraction of a second, mostly waiting for the network. Asking one after another wastes time. Go makes it easy to start many tasks at once. A goroutine is a function running concurrently, started with the keyword go in front of a call, and it is so lightweight that programs routinely run thousands of them. Goroutines communicate through channels, typed pipes: ch <- v sends a value, v := <-ch receives one, and the proverb of the language says to share memory by communicating, not to communicate by sharing memory.

An unbuffered channel makes the sender and the receiver meet: a send waits until someone receives. A buffered channel, made with make(chan int, 10), accepts that many values before a send blocks. Closing a channel with close tells receivers that no more values will come, and a for range loop over the channel ends when it is closed and drained. A sync.WaitGroup counts running goroutines, so that a function can wait for all of them. The select statement waits on several channel operations at once and runs the first that is ready, and together with time.After it gives you timeouts. When main returns, the program ends, even if goroutines are still running.

Tool Use
go f() Start a goroutine
ch := make(chan T) An unbuffered channel
ch <- v, v := <-ch Send and receive
close(ch), for v := range ch Signal and drain
sync.WaitGroup Wait for a set of goroutines
select { case … } Wait on several channels
package main

import (
	"fmt"
	"sort"
	"sync"
	"time"
)

func check(id int) int {
	time.Sleep(50 * time.Millisecond)
	return id * id
}

func main() {
	start := time.Now()
	seq := 0
	for i := 1; i <= 10; i++ {
		seq += check(i)
	}
	seqTime := time.Since(start)

	start = time.Now()
	results := make(chan int, 10)
	var wg sync.WaitGroup
	for i := 1; i <= 10; i++ {
		wg.Add(1)
		go func(id int) {
			defer wg.Done()
			results <- check(id)
		}(i)
	}
	go func() { wg.Wait(); close(results) }()
	var got []int
	con := 0
	for r := range results {
		got = append(got, r)
		con += r
	}
	conTime := time.Since(start)
	sort.Ints(got)
	fmt.Println("sequential sum of squares:", seq, "| concurrent:", con, "| results:", got)
	fmt.Println("sequential took at least 500 ms:", seqTime >= 500*time.Millisecond)
	fmt.Println("concurrent took under 250 ms:", conTime < 250*time.Millisecond)

	gen := func(n int) <-chan int {
		out := make(chan int)
		go func() {
			for i := 1; i <= n; i++ {
				out <- i
			}
			close(out)
		}()
		return out
	}
	square := func(in <-chan int) <-chan int {
		out := make(chan int)
		go func() {
			for v := range in {
				out <- v * v
			}
			close(out)
		}()
		return out
	}
	total := 0
	for v := range square(gen(5)) {
		total += v
	}
	fmt.Println("pipeline gen -> square -> sum of 1..5 squared:", total)

	slow := make(chan string)
	go func() { time.Sleep(300 * time.Millisecond); slow <- "late answer" }()
	select {
	case m := <-slow:
		fmt.Println("received:", m)
	case <-time.After(60 * time.Millisecond):
		fmt.Println("select gave up after the timeout")
	}
}
sequential sum of squares: 385 | concurrent: 385 | results: [1 4 9 16 25 36 49 64 81 100]
sequential took at least 500 ms: true
concurrent took under 250 ms: true
pipeline gen -> square -> sum of 1..5 squared: 55
select gave up after the timeout

Both versions produced the same answer, 385, the sum of the squares of 1 to 10, and the sorted results are [1 4 9 16 25 36 49 64 81 100]. The difference is the waiting. Ten checks of 50 milliseconds one after another took at least half a second, and started together in ten goroutines they finished in a little over one wait, under a quarter of a second. Timings depend on the machine, so the program prints only comparisons that hold with a wide margin. The results arrived through a buffered channel in whatever order the goroutines finished, which is why the program sorted them before printing: concurrent code does not promise an order unless you create one.

The pipeline connected three stages with channels: one goroutine generated the numbers 1 to 5, the next squared them, and main summed them, giving 55. Each stage closes its output channel when done, which is what lets the next stage’s range loop end. The last experiment used select with time.After: the slow goroutine needed 300 milliseconds, and the select gave up after 60 and moved on, so the program is never stuck forever waiting for a slow partner.

Check by hand: 1 + 4 + 9 + … + 100 = 385, and 1 + 4 + 9 + 16 + 25 = 55. Ten sleeps of 50 ms in a row are 500 ms, while ten that overlap take about 50 ms.

A goroutine that blocks forever is a leak

If nobody ever receives from a channel that a goroutine sends to, the goroutine waits forever and its memory is never freed. Always make sure that every goroutine can finish, for example with a done channel or a context.

Pass values to goroutines as arguments

In the loop above, go func(id int) { … }(i) gives each goroutine its own copy of i. Go 1.22 changed loop variables to be per iteration, but passing arguments is clear in every version.

About this course

Every program in this lesson was built and run with Go 1.24 while the course was written. Go releases twice a year, so check go.dev for the current version and release notes. The timing checks compare against wide margins so that they hold on slow machines.

Practice

Write a worker that reads job numbers from a channel and sends squares to another, and start three of them. Add a timeout with select around a receive. Remove the close call from the pipeline and see what happens, then fix it.

Check what you learned

Five quick questions. Pick an answer and you will see straight away whether it is right and why.

What does the go keyword do?

  1. Starts a function in a new goroutine
  2. Jumps to a label
  3. Imports a package
  4. Declares a variable

Goroutines are lightweight.

What does closing a channel signal?

  1. The program ends
  2. An error
  3. The channel is empty
  4. No more values will be sent

range loops end when it is drained.

Why were the results sorted before printing?

  1. Channels sort by themselves
  2. Sorting is required
  3. To save memory
  4. Goroutines finish in no fixed order

Concurrent order is not promised.

What does select with time.After provide?

  1. A faster loop
  2. A lock
  3. A timeout
  4. A new goroutine

It stopped waiting after 60 ms.

What does sync.WaitGroup do?

  1. Locks a variable
  2. Creates channels
  3. Waits for a set of goroutines to finish
  4. Sorts results

Add, Done and Wait.

Summary

  • Goroutines run concurrently; channels pass values between them.
  • close and range end a stream of values.
  • WaitGroup waits; select with time.After gives timeouts.
  • Concurrent order is not guaranteed unless you create it.

Next lesson

Lesson 9 covers shared data, mutexes and the race detector.

Questions

How many goroutines can I start?

Many thousands is normal, because each starts with a very small stack. The practical limit is memory and what the goroutines do.

What is the difference between concurrency and parallelism?

Concurrency is structuring a program as independent tasks. Parallelism is running them at the same moment on several processors. Go gives you the first and uses the second when processors are available.

Should I use channels or mutexes?

Use channels for passing ownership and coordinating, and mutexes for protecting shared state. Lesson 9 covers mutexes.

Progress is saved in this browser.