---
title: "Goroutines and channels: work at the same time"
slug: "goroutines-and-channels"
description: "Start goroutines with go, wait with sync.WaitGroup, pass values over channels, build a small pipeline and use select. Fix a deadlock."
published: "2026-12-03"
updated: "2026-12-03"
canonical: "https://aifree.dev/courses/learn-go/goroutines-and-channels"
---

# Goroutines and channels: work at the same time

How does Go run several things at once without shared-memory bugs?

## Predict

```go
package main

import "fmt"

func main() {
	ch := make(chan int)
	go func() {
		for i := 1; i <= 3; i++ {
			ch <- i
		}
		close(ch)
	}()
	for v := range ch {
		fmt.Println(v)
	}
}
```

What does this program print?

- The numbers in random order
- It stops with a deadlock error
- 1, 2 and 3, each on its own line

Answer: 1, 2 and 3, each on its own line — The goroutine sends 1, 2, 3 in order and closes the channel. main prints each one as it arrives.

Output:

```
1
2
3
```

The channel keeps the order of sends. The range loop ends when the goroutine closes the channel.

## Goroutines

Put `go` before a function call and it runs as a **goroutine**, at the same time as the rest of your code. When `main` returns, the program ends, even if goroutines are still running. To wait for them, use a `sync.WaitGroup`: call `wg.Add(1)` before starting, `defer wg.Done()` inside the goroutine and `wg.Wait()` where you need all of them finished.

## Three workers and a WaitGroup

```go
package main

import (
	"fmt"
	"sync"
)

func main() {
	results := make(chan int, 3)
	var wg sync.WaitGroup
	for i := 1; i <= 3; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			results <- i * i
		}()
	}
	wg.Wait()
	close(results)

	sum := 0
	for r := range results {
		sum += r
	}
	fmt.Println("sum:", sum)
}
```

Output:

```
sum: 14
```

The workers may finish in any order, so the program prints only the sum, which is always 14. The channel is buffered so the sends never wait.

Playground: https://go.dev/play/p/GnOiMPnWdYH

## Channels

A **channel** moves values between goroutines: `ch <- v` sends and `v := <-ch` receives. On an unbuffered channel, a send waits until another goroutine receives. A buffered channel, `make(chan int, 3)`, lets sends continue until it is full. `close(ch)` tells receivers no more values come, and `range` stops then. `select` waits on several channels; `default` runs when none is ready.

## A pipeline and a select

```go
package main

import "fmt"

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

func square(in <-chan int) <-chan int {
	out := make(chan int)
	go func() {
		for v := range in {
			out <- v * v
		}
		close(out)
	}()
	return out
}

func main() {
	for v := range square(generate(4)) {
		fmt.Println(v)
	}

	empty := make(chan int)
	select {
	case v := <-empty:
		fmt.Println("got", v)
	default:
		fmt.Println("nothing ready")
	}
}
```

Output:

```
1
4
9
16
nothing ready
```

`generate` and `square` each run a goroutine and return a receive-only channel, `<-chan int`. The `default` case lets `select` skip a channel that has nothing.

Playground: https://go.dev/play/p/wBN9SzWdGck

## Fix it

```go
package main

import "fmt"

func main() {
	ch := make(chan int)
	ch <- 1
	fmt.Println(<-ch)
}
```

The program stops with a deadlock. What is wrong?

- The channel needs a larger buffer size
- main sends on an unbuffered channel, but no other goroutine can receive
- Println cannot read from a channel

Answer: main sends on an unbuffered channel, but no other goroutine can receive — The send waits for a receiver that never comes. Send from a goroutine instead.

Compiler message:

```
fatal error: all goroutines are asleep - deadlock!
```

Fixed:

```go
package main

import "fmt"

func main() {
	ch := make(chan int)
	go func() {
		ch <- 1
	}()
	fmt.Println(<-ch)
}
```

Output:

```
1
```

## Say it back

In your own words: why does a send on an unbuffered channel block?

Our sentence: An unbuffered channel has no room to hold a value, so the sender waits until another goroutine is ready to receive it.

## Mission (12 min)

Build a worker pool: three workers read the numbers 1 to 9 from a jobs channel and send their squares to a results channel. Add up the results and print the total, which must be 285.

```sh
go run .
```

## Common questions

### What is a goroutine?

A goroutine is a function running at the same time as other code in the same program. You start one by putting go before a call. Goroutines are cheap, so a program can run thousands of them. They share memory, so Go advice is to pass values over channels instead of sharing variables, which avoids many timing bugs.

### Why does my program end before the goroutine prints?

When main returns, the whole program exits, and it does not wait for goroutines that are still running. You must make main wait. The usual tools are a sync.WaitGroup, which counts running goroutines, or a channel that main receives from. A sleep is not a fix, because it only guesses how long the work takes.

### When should I close a channel?

Close a channel when the sender has no more values, so receivers using range or the two-value receive know to stop. Only the sender should close it, and never more than once, or the program panics. You do not have to close a channel for cleanup; the garbage collector frees it when nothing uses it.

## Sources

- https://go.dev/ref/spec#Go_statements (read 2026-12-03)
- https://go.dev/ref/spec#Channel_types (read 2026-12-03)
- https://pkg.go.dev/sync#WaitGroup (read 2026-12-03)

Measured with go1.27.4 darwin/arm64 on 2026-12-03.
