Learn to Code
All tracks
Learn to Code

Free lessons from scratch to pro — every language, databases and DevOps.

AboutContactPrivacy PolicyTerms of Use

Your progress is saved in this browser. © 2026 Learn to Code

GO
Go
0/12 completed
Beginner
Hello GoTypes and variablesControl flowFunctions
Intermediate
Arrays, slices and mapsStructs and methodsInterfacesError handling
Advanced
GenericsGoroutines and channels
Pro
Building an HTTP serverModules, testing and tooling
Tracks / Go / Advanced

Goroutines and channels

Concurrency is where Go really stands out. A goroutine is a function running at the same time as others. It's so cheap (a few KB of memory) that a program can run hundreds of thousands of them. Channels let goroutines send each other values safely. Together they make it straightforward to fetch 50 URLs at once, process a queue with a pool of workers, or serve thousands of connections.

Starting goroutines

Put go in front of a function call and it runs concurrently. A sync.WaitGroup waits for a group of goroutines to finish:

go
package main

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

func download(name string, ms int) {
	time.Sleep(time.Duration(ms) * time.Millisecond)   // pretend to work
	fmt.Println("finished", name)
}

func main() {
	start := time.Now()
	var wg sync.WaitGroup
	files := map[string]int{"a.csv": 300, "b.csv": 100, "c.csv": 200}
	for name, ms := range files {
		wg.Go(func() { download(name, ms) })
	}
	wg.Wait()
	fmt.Printf("all done in about %.1fs (one after another would take 0.6s)\n", time.Since(start).Seconds())
}
Output
finished b.csv
finished c.csv
finished a.csv
all done in about 0.3s (one after another would take 0.6s)
  • The three downloads ran at the same time, so the total was the longest one (0.3 s), not the sum.
  • They finished in order of duration, not the order they started: goroutines run independently.
  • wg.Go(f) (Go 1.25+) starts f in a goroutine and tracks it; wg.Wait() blocks until all are done. (Older code writes wg.Add(1), go func() { defer wg.Done(); … }().)
  • When main returns, the program exits, even if goroutines are still running. That's why you must wait for them.

Channels

A channel is a typed pipe between goroutines. Sending (ch <- v) and receiving (v := <-ch) wait until the other side is ready, so channels both pass data and synchronise:

go
package main

import "fmt"

func square(n int, results chan<- int) {
	results <- n * n            // send
}

func main() {
	results := make(chan int)
	for i := 1; i <= 3; i++ {
		go square(i, results)
	}
	sum := 0
	for range 3 {
		sum += <-results        // receive (in whatever order they arrive)
	}
	fmt.Println("sum of squares:", sum)
}
Output
sum of squares: 14

chan<- int in a parameter means "this function may only send". Arrow direction shows the data flow.

Closing and ranging

The sender closes a channel to say "no more values"; for v := range ch receives until then:

go
package main

import "fmt"

func generate(n int) <-chan int {
	out := make(chan int)
	go func() {
		defer close(out)
		for i := range n {
			out <- i
		}
	}()
	return out
}

func main() {
	for v := range generate(5) {
		fmt.Print(v, " ")
	}
	fmt.Println()

	v, ok := <-generate(0)     // receiving from a closed channel: zero value, ok=false
	fmt.Println(v, ok)
}
Output
0 1 2 3 4
0 false

Buffered channels

make(chan T, n) creates a channel that can hold n values without a receiver waiting. Sends only block when the buffer is full:

go
package main

import "fmt"

func main() {
	jobs := make(chan string, 3)
	jobs <- "resize"
	jobs <- "upload"
	fmt.Println(len(jobs), "queued, capacity", cap(jobs))
	close(jobs)
	for j := range jobs {
		fmt.Println("doing", j)
	}
}
Output
2 queued, capacity 3
doing resize
doing upload

A worker pool

The most common concurrency pattern: a fixed number of workers take jobs from one channel and send results to another. It limits how much runs at once, which keeps you from opening 10,000 connections to a database:

go
package main

import (
	"fmt"
	"slices"
	"sync"
)

type Result struct {
	Job    int
	Output int
	Worker int
}

func worker(id int, jobs <-chan int, results chan<- Result) {
	for j := range jobs {
		results <- Result{Job: j, Output: j * j, Worker: id}
	}
}

func main() {
	jobs := make(chan int)
	results := make(chan Result)

	var wg sync.WaitGroup
	for id := 1; id <= 3; id++ {
		wg.Go(func() { worker(id, jobs, results) })
	}

	go func() {                         // feed the jobs, then close
		for j := 1; j <= 9; j++ {
			jobs <- j
		}
		close(jobs)
	}()
	go func() { wg.Wait(); close(results) }()   // close results when every worker is done

	var all []Result
	for r := range results {
		all = append(all, r)
	}
	slices.SortFunc(all, func(a, b Result) int { return a.Job - b.Job })
	total := 0
	for _, r := range all {
		total += r.Output
		fmt.Printf("job %d → %d  ", r.Job, r.Output)
	}
	fmt.Println("\ntotal:", total, "from", len(all), "jobs")
}
Output
job 1 → 1  job 2 → 4  job 3 → 9  job 4 → 16  job 5 → 25  job 6 → 36  job 7 → 49  job 8 → 64  job 9 → 81
total: 285 from 9 jobs

Which worker handled which job changes on every run, so the results are sorted before printing. The shape (jobs channel, N workers, results channel, close when done) is worth memorising.

select: waiting on several channels

select waits until one of several channel operations can proceed. With time.After, it gives you timeouts:

go
package main

import (
	"fmt"
	"time"
)

func fetch(delay time.Duration) <-chan string {
	ch := make(chan string, 1)
	go func() {
		time.Sleep(delay)
		ch <- fmt.Sprintf("response after %v", delay)
	}()
	return ch
}

func main() {
	for _, d := range []time.Duration{50 * time.Millisecond, 500 * time.Millisecond} {
		select {
		case r := <-fetch(d):
			fmt.Println(r)
		case <-time.After(200 * time.Millisecond):
			fmt.Println("timed out after 200ms")
		}
	}
}
Output
response after 50ms
timed out after 200ms

A default: case makes select non-blocking: it runs immediately if no channel is ready.

Cancellation with context

Real programs need to stop work that's no longer wanted: the user cancelled the request, or the deadline passed. A context.Context carries that signal to every goroutine involved:

go
package main

import (
	"context"
	"errors"
	"fmt"
	"time"
)

func slowQuery(ctx context.Context, steps int) error {
	for i := 1; i <= steps; i++ {
		select {
		case <-ctx.Done():
			return fmt.Errorf("query stopped at step %d: %w", i, ctx.Err())
		case <-time.After(50 * time.Millisecond):    // one step of work
		}
	}
	return nil
}

func main() {
	ctx, cancel := context.WithTimeout(context.Background(), 180*time.Millisecond)
	defer cancel()

	fmt.Println("short query:", slowQuery(ctx, 2))
	err := slowQuery(ctx, 10)
	fmt.Println("long query:", err)
	fmt.Println("deadline exceeded?", errors.Is(err, context.DeadlineExceeded))
}
Output
short query: <nil>
long query: query stopped at step 2: context deadline exceeded
deadline exceeded? true

By convention, ctx context.Context is the first parameter of any function that does I/O or might take a while. HTTP servers give every request a context that's cancelled when the client disconnects, and database and HTTP client libraries all accept one.

Shared memory and the race detector

Goroutines that change the same variable without coordination cause a data race: results become wrong in unpredictable ways.

race.go
package main

import (
	"fmt"
	"sync"
)

func main() {
	count := 0
	var wg sync.WaitGroup
	for range 1000 {
		wg.Go(func() { count++ })      // many goroutines, one variable: a race
	}
	wg.Wait()
	fmt.Println("count:", count)
}
bash
go run -race race.go
Output
Found N data race(s)
WARNING: DATA RACE
exit status 66

Go's built-in race detector (-race, for go run, go test and go build) catches it. Run your tests with -race. There are two fixes. Either protect the variable with a mutex:

go
package main

import (
	"fmt"
	"sync"
	"sync/atomic"
)

type Counter struct {
	mu sync.Mutex
	n  map[string]int
}

func (c *Counter) Inc(key string) {
	c.mu.Lock()
	defer c.mu.Unlock()
	c.n[key]++
}

func main() {
	c := Counter{n: map[string]int{}}
	var hits atomic.Int64
	var wg sync.WaitGroup
	for i := range 1000 {
		wg.Go(func() {
			c.Inc([]string{"home", "about"}[i%2])
			hits.Add(1)
		})
	}
	wg.Wait()
	fmt.Println(c.n, hits.Load())
}
Output
map[about:500 home:500] 1000

…or don't share at all: give the data to one goroutine and send it messages over channels. The Go proverb: "Don't communicate by sharing memory; share memory by communicating." For a single number, the sync/atomic types (atomic.Int64) are the simplest fix.

errgroup: goroutines that can fail

The golang.org/x/sync/errgroup package combines a WaitGroup, the first error, and context cancellation, and it's the standard tool for "run these tasks concurrently, stop if one fails". You'll install packages like it in Modules, testing and tooling:

go
g, ctx := errgroup.WithContext(ctx)
for _, url := range urls {
	g.Go(func() error { return fetch(ctx, url) })
}
if err := g.Wait(); err != nil {   // the first error; ctx was cancelled for the others
	return err
}

Practice

  1. Fetch three "pages" concurrently (simulate with time.Sleep) and print how long it took in total.
  2. Build a pipeline: one goroutine generates numbers, a second squares them, main prints them. Connect them with channels and close each channel when done.
  3. Write a worker pool that counts the words in a list of strings with 4 workers.
  4. Add a 1-second timeout to a slow function using context.WithTimeout, and check for context.DeadlineExceeded.
✎ Check your understanding

1.What does go doWork() do?

2.What happens to running goroutines when main returns?

3.Who should close a channel?

4.How do you find data races?

← Generics