Part 6. ConcurrencyLesson 17# go# concurrency# goroutines# channels# interview

Concurrency — goroutines and channels

goroutines, WaitGroup, channels, select, Mutex, worker pool, context

Цели главы

  • Запускать горутины и правильно дожидаться их через WaitGroup.
  • Понимать небуферизованные и буферизованные каналы, close и range по каналу.
  • Ждать нескольких событий и таймаутов через select.
  • Защищать общие данные мьютексом и писать worker pool.
  • Отменять работу через context.

Горутины

Как GoFlix одновременно грузит обложки, считает рекомендации и стримит фильмы тысячам пользователей? Go создавали для многопоточности, но вместо тяжёлых потоков операционной системы в нём горутины: лёгкие, стартуют с маленьким стеком в пару килобайт, который растёт по мере необходимости. Запускаются словом go и управляются планировщиком Go.

Планировщик работает по схеме M:N: множество горутин распределяется на меньшее число потоков ОС, и Go сам переключает их. Поэтому тысячи горутин почти ничего не стоят по памяти и эффективно загружают все ядра процессора.

горутины — тысячиG1G2G3G4P — контексты планировщикапо числу ядер (GOMAXPROCS)P1 + очередь горутинP2 + очередь горутинM — потоки ОСM1M2

main — тоже горутина

Когда main завершается, программа заканчивается вместе со всеми горутинами — даже незаконченными. Если main закончится слишком быстро, вывод горутин может вообще не появиться.

go
package main

import (
    "fmt"
    "time"
)

func main() {
    go fmt.Println("привет из горутины")
    go func() {
        fmt.Println("привет из анонимной горутины")
    }()
    time.Sleep(100 * time.Millisecond) // только для демонстрации
    fmt.Println("main завершается")
    // недетерминированный вывод: порядок первых двух строк может меняться
}

Пример вывода:

text
привет из анонимной горутины
привет из горутины
main завершается

sync.WaitGroup

WaitGroup — счётчик активных горутин:

  • wg.Add(1) — увеличить счётчик перед запуском горутины;
  • wg.Done() — уменьшить, когда горутина закончила; обычно через defer;
  • wg.Wait() — заблокировать вызывающую горутину, пока счётчик не станет нулём.
go
package main

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

func main() {
    movies := []string{"Интерстеллар", "Дюна", "Начало"}
    var wg sync.WaitGroup

    for i, movie := range movies {
        wg.Add(1) // до запуска горутины
        go func() {
            defer wg.Done() // уменьшит счётчик при любом выходе
            time.Sleep(time.Duration(30*(len(movies)-i)) * time.Millisecond)
            fmt.Println("загружен постер:", movie)
        }()
    }

    wg.Wait() // ждём, пока все горутины не закончат
    fmt.Println("все постеры загружены")
    // недетерминированный вывод: кто закончил раньше, тот и печатает
}

Пример вывода:

text
загружен постер: Начало
загружен постер: Дюна
загружен постер: Интерстеллар
все постеры загружены

Горутины работают конкурентно, поэтому сообщения появляются в порядке завершения, а не запуска. Главное — wg.Wait() после цикла: дальше main пойдёт только после всех Done.

Каналы

Go предлагает обмениваться данными через каналы — по девизу «Не общайтесь через разделяемую память — разделяйте память через общение». Канал типизирован: по chan string ходят только строки.

  • Создать: ch := make(chan string).
  • Отправить: ch <- v. Получить: v := <-ch.
  • В небуферизованном канале отправка блокирует горутину, пока другая не прочитает значение, а чтение блокирует, пока значение не отправят. Отправитель и получатель встречаются в одной точке синхронизации.
go
package main

import "fmt"

func average(ratings []float64) float64 {
    sum := 0.0
    for _, r := range ratings {
        sum += r
    }
    return sum / float64(len(ratings))
}

func main() {
    messages := make(chan string) // небуферизованный канал строк

    go func() {
        messages <- "Матрица загружена" // отправка ждёт, пока кто-то прочитает
    }()
    fmt.Println(<-messages) // чтение ждёт, пока кто-то отправит

    avgCh := make(chan float64)
    go func() {
        avgCh <- average([]float64{8.7, 9.0, 8.1})
    }()
    fmt.Printf("средний рейтинг: %.2f\n", <-avgCh)
}
stdout // вывод программы
Матрица загружена
средний рейтинг: 8.60

Канал в Go — не просто контейнер, а способ безопасно передать значение и одновременно синхронизировать горутины.

Буферизованный канал

Если отправителю не нужно ждать получателя на каждом сообщении, канал создают с буфером: make(chan T, N). Отправка блокируется, только когда буфер полон, чтение — когда пуст. По сути, это небольшая очередь: отправитель может «забежать вперёд». Удобно, когда сообщения приходят пачками.

go
package main

import "fmt"

func main() {
    notifications := make(chan string, 3)
    notifications <- "Новый фильм: Дюна 2"
    notifications <- "Скидка 50%!"
    notifications <- "Новый сезон: Мандалорец"
    // notifications <- "ещё одно" — заблокировало бы: буфер полон

    fmt.Println(len(notifications), "из", cap(notifications), "в очереди")
    fmt.Println(<-notifications)
    fmt.Println(<-notifications)
    fmt.Println(len(notifications), "в очереди")
}
stdout // вывод программы
3 из 3 в очереди
Новый фильм: Дюна 2
Скидка 50%!
1 в очереди

close и range по каналу

close(ch) сообщает получателям: значений больше не будет.

  • Цикл for v := range ch читает, пока канал не закрыт и не пуст, а потом сам завершается. Уже отправленные значения закрытие не удаляет.
  • Чтение из закрытого и пустого канала возвращает нулевое значение и ok == false.
  • Отправка в закрытый канал — паника send on closed channel.
  • Закрывает канал только отправитель, получатель — никогда.
go
package main

import "fmt"

func main() {
    moviesCh := make(chan string)
    go func() {
        defer close(moviesCh) // закрывает отправитель: «данных больше не будет»
        for _, m := range []string{"Матрица", "Начало", "Довод"} {
            moviesCh <- m
        }
    }()
    for movie := range moviesCh { // цикл завершится после close
        fmt.Println("получен:", movie)
    }

    done := make(chan int)
    close(done)
    val, ok := <-done // закрытый и пустой: нулевое значение и false
    fmt.Println("значение:", val, "открыт?", ok)
}
stdout // вывод программы
получен: Матрица
получен: Начало
получен: Довод
значение: 0 открыт? false
go
package main

func main() {
    ch := make(chan int, 1)
    close(ch)
    ch <- 1 // ожидается panic
}
text
panic: send on closed channel

Если отправителей несколько, закрывать канал можно только когда все закончили отправку — для этого WaitGroup и отдельная горутина, которая закроет канал после wg.Wait():

go
package main

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

func main() {
    results := make(chan string)
    var wg sync.WaitGroup
    for _, film := range []string{"Дюна", "Матрица", "Начало"} {
        wg.Add(1)
        go func() {
            defer wg.Done()
            results <- film + ": обложка готова"
        }()
    }
    go func() {
        wg.Wait()      // все отправители закончили
        close(results) // теперь закрывать безопасно
    }()

    var all []string
    for r := range results {
        all = append(all, r)
    }
    slices.Sort(all) // горутины финишируют в любом порядке
    fmt.Println(all)
}
stdout // вывод программы
[Дюна: обложка готова Матрица: обложка готова Начало: обложка готова]

Сигнальный канал

Если передавать данные не нужно, а важен сам факт события — «работа закончена», «пора остановиться», — используют канал пустых структур chan struct{}. Сигнал — отправка struct{}{} или закрытие канала. Закрытие удобнее: его «услышат» сразу все ждущие горутины.

go
package main

import (
    "fmt"
    "time"
)

func main() {
    done := make(chan struct{}) // данных нет — важен только сигнал
    go func() {
        fmt.Println("горутина работает...")
        time.Sleep(50 * time.Millisecond)
        close(done) // сигнал всем, кто ждёт
    }()
    <-done
    fmt.Println("main: получили сигнал завершения")
}
stdout // вывод программы
горутина работает...
main: получили сигнал завершения

select

select похож на switch, но для каналов: ждёт, пока один из каналов будет готов, и выполняет его case.

  • Готовы несколько — выбирается случайный.
  • Не готов ни один и нет default — select блокируется.
  • default делает select неблокирующим: если данных нет, сразу идём дальше.
  • time.After(d) — канал, в который придёт значение через d: так ограничивают время ожидания.
go
package main

import (
    "fmt"
    "time"
)

func fetch(delay time.Duration, movie string) <-chan string {
    ch := make(chan string, 1) // буфер 1: горутина не зависнет, если результат не прочитают
    go func() {
        time.Sleep(delay)
        ch <- movie
    }()
    return ch
}

func main() {
    select {
    case movie := <-fetch(50*time.Millisecond, "Интерстеллар"):
        fmt.Println("рекомендация:", movie)
    case <-time.After(200 * time.Millisecond):
        fmt.Println("таймаут: сервис рекомендаций не ответил")
    }

    select {
    case movie := <-fetch(300*time.Millisecond, "Дюна"):
        fmt.Println("рекомендация:", movie)
    case <-time.After(100 * time.Millisecond):
        fmt.Println("таймаут: сервис рекомендаций не ответил")
    }

    empty := make(chan string)
    select {
    case msg := <-empty:
        fmt.Println(msg)
    default:
        fmt.Println("данных нет — идём дальше") // default делает select неблокирующим
    }
}
stdout // вывод программы
рекомендация: Интерстеллар
таймаут: сервис рекомендаций не ответил
данных нет — идём дальше

select без default — когда действительно нужно дождаться одного из событий; с default — когда нужно проверить каналы и не ждать.

sync.Mutex

Иногда удобнее не передавать данные, а защитить общий ресурс. sync.Mutex (взаимное исключение) гарантирует, что с ресурсом работает только одна горутина, а остальные ждут. Lock() — вход в критическую секцию, Unlock() — выход; defer Unlock() сразу после Lock() освободит мьютекс при любом выходе, даже при панике.

go
package main

import (
    "fmt"
    "sync"
)

// ViewCounter — потокобезопасный счётчик просмотров.
type ViewCounter struct {
    mu    sync.Mutex
    count int
}

func (vc *ViewCounter) Increment() {
    vc.mu.Lock()
    defer vc.mu.Unlock() // освободим при любом выходе
    vc.count++
}

func (vc *ViewCounter) Value() int {
    vc.mu.Lock()
    defer vc.mu.Unlock()
    return vc.count
}

func main() {
    counter := &ViewCounter{}
    var wg sync.WaitGroup
    for range 1000 {
        wg.Add(1)
        go func() {
            defer wg.Done()
            counter.Increment()
        }()
    }
    wg.Wait()
    fmt.Println("просмотров:", counter.Value())
}
stdout // вывод программы
просмотров: 1000

Даже чтение защищено мьютексом, чтобы получить согласованное значение. Без мьютекса несколько горутин одновременно читали бы и меняли одно поле — это гонка данных (data race), и итог мог бы оказаться меньше 1000.

Worker Pool

Задач много, но запускать горутину на каждую — плохая идея: можно перегрузить базу или внешний сервис. Worker pool — фиксированное число горутин-воркеров, которые берут задачи из канала jobs и кладут результаты в results. Отправив все задачи, канал jobs закрывают: когда он опустеет, цикл range у каждого воркера завершится. Паттерн ограничивает число одновременных операций и упрощает контроль ресурсов.

go
package main

import (
    "fmt"
    "time"
)

// worker обрабатывает задачи из jobs, пока канал не закрыт и не пуст.
func worker(id int, jobs <-chan string, results chan<- string) {
    for film := range jobs {
        time.Sleep(10 * time.Millisecond) // «обработка»
        results <- fmt.Sprintf("воркер %d обработал: %s", id, film)
    }
}

func main() {
    films := []string{"Дюна", "Матрица", "Довод", "Начало", "Аватар"}
    jobs := make(chan string, len(films))
    results := make(chan string, len(films))

    for w := 1; w <= 3; w++ { // ровно три воркера, сколько бы ни было задач
        go worker(w, jobs, results)
    }

    for _, f := range films {
        jobs <- f
    }
    close(jobs) // сигнал: задач больше не будет

    for range films { // столько чтений, сколько задач
        fmt.Println(<-results)
    }
    // недетерминированный вывод: какой воркер что взял — решает планировщик
}

Пример вывода:

text
воркер 3 обработал: Дюна
воркер 1 обработал: Матрица
воркер 2 обработал: Довод
воркер 2 обработал: Аватар
воркер 3 обработал: Начало

Порядок результатов каждый раз разный: кто из воркеров быстрее закончил, тот раньше и отправил результат. Типы <-chan string и chan<- string — каналы только для чтения и только для записи: компилятор не даст воркеру случайно писать в jobs.

context — отмена и дедлайны

В реальных сервисах работу приходится отменять: пользователь ушёл, истёк таймаут, запрос отменили. Пакет context передаёт сигнал отмены и дедлайн.

Функция Когда контекст отменится
context.WithCancel(parent) при вызове cancel() или отмене родителя
context.WithTimeout(parent, d) через время d
context.WithDeadline(parent, t) в момент времени t

ctx.Done() возвращает канал, который закрывается при отмене; ctx.Err() объясняет причину: context canceled или context deadline exceeded. Функция cancel вызывается всегда, обычно через defer, — она освобождает ресурсы контекста.

go
package main

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

func slowRecommendations(ctx context.Context, delay time.Duration) (string, error) {
    select {
    case <-time.After(delay): // «долгая» работа
        return "Интерстеллар, Дюна", nil
    case <-ctx.Done(): // отмена или дедлайн
        return "", ctx.Err()
    }
}

func main() {
    ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
    defer cancel() // освобождаем ресурсы контекста в любом случае

    res, err := slowRecommendations(ctx, 50*time.Millisecond)
    fmt.Println("успели:", res, err)

    res, err = slowRecommendations(ctx, 300*time.Millisecond)
    fmt.Printf("не успели: %q, %v\n", res, err)

    ctx2, cancel2 := context.WithCancel(context.Background())
    var wg sync.WaitGroup
    wg.Add(1)
    go func() {
        defer wg.Done()
        for {
            select {
            case <-ctx2.Done():
                fmt.Println("стриминг остановлен:", ctx2.Err())
                return
            default:
                time.Sleep(20 * time.Millisecond) // «стримим» кусок фильма
            }
        }
    }()
    time.Sleep(70 * time.Millisecond)
    cancel2() // ручная отмена — горутина завершится
    wg.Wait()
}
stdout // вывод программы
успели: Интерстеллар, Дюна <nil>
не успели: "", context deadline exceeded
стриминг остановлен: context canceled

context не просто ждёт завершения задачи, а управляет её жизненным циклом: останавливает по таймауту, по дедлайну или по команде. В бэкенде контекст передают первым параметром во все функции, которые ходят в сеть или в базу, — см. 19 — Работа с базами данных → Context во всём приложении.

Итоги

Инструмент Зачем Ключевые детали
Горутина лёгкая конкурентная функция go f(), стек от пары КБ, планировщик M:N
sync.WaitGroup дождаться группы горутин Add до запуска, defer Done, Wait до нуля
Канал безопасный обмен данными небуферизованный — встреча; буферизованный — очередь
close и range конец потока данных закрывает отправитель; запись в закрытый — паника
select ждать несколько каналов случайный из готовых; default — без ожидания
sync.Mutex защитить общие данные Lock + defer Unlock
Worker pool ограничить параллелизм N воркеров читают jobs, пишут results
context отмена и дедлайны WithCancel, WithTimeout, Done(), Err()

Практика

Домашнее задание

  1. Параллельная проверка эпизодов. Функция checkEpisode(title string, delay int, wg *sync.WaitGroup) имитирует проверку через time.Sleep и сообщает, что эпизод готов к публикации. Запусти горутину на каждый эпизод, дождись всех через WaitGroup и выведи, что все эпизоды проверены.
  2. Статусы транскодирования через канал. Функция transcodeVideo(name string, ch chan string) имитирует транскодирование и отправляет в канал строку-результат. Запусти горутину на каждый файл, собери результаты из канала и выведи. Без time.Sleep для ожидания.
  3. Очередь событий плеера. Буферизованный канал строк, события play, pause, seek, stop. Отправь все, закрой канал, прочитай циклом for range, в конце сообщи, что очередь обработана.
  4. Предпочтения с таймаутом. loadUserTaste после задержки отправляет в канал описание предпочтений. Через select либо получи результат, либо по таймауту сообщи, что предпочтения пока недоступны.
  5. Мини-аналитика. События: просмотр начат, остановлен, завершён, лайк поставлен, добавлено в избранное. Канал jobs, канал results, несколько воркеров; закрой jobs после отправки, собери результаты, дождись воркеров через WaitGroup; посчитай обработанные события под мьютексом; добавь context.WithTimeout и, если время вышло, прекрати обработку и сообщи об отмене.
решениеЭталонное решение

Задание 1 — порядок завершения эпизодов зависит от задержек и планировщика:

go
package main

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

func checkEpisode(title string, delay int, wg *sync.WaitGroup) {
    defer wg.Done()
    time.Sleep(time.Duration(delay) * time.Millisecond) // имитация проверки
    fmt.Printf("эпизод %q готов к публикации\n", title)
}

func main() {
    episodes := map[string]int{"Пилот": 30, "Эпизод 2": 10, "Финал": 20}
    var wg sync.WaitGroup
    for title, delay := range episodes {
        wg.Add(1)
        go checkEpisode(title, delay, &wg)
    }
    wg.Wait()
    fmt.Println("все эпизоды проверены успешно")
    // недетерминированный вывод: эпизоды завершаются в разном порядке
}

Пример вывода:

text
эпизод "Эпизод 2" готов к публикации
эпизод "Финал" готов к публикации
эпизод "Пилот" готов к публикации
все эпизоды проверены успешно

Задания 2–5:

go
package main

import (
    "context"
    "errors"
    "fmt"
    "slices"
    "strings"
    "sync"
    "time"
)

// Задание 2: транскодирование, результаты через канал.
func transcodeVideo(name string, ch chan<- string) {
    time.Sleep(time.Duration(len(name)) * time.Millisecond) // имитация работы
    ch <- name + " → 1080p готово"
}

// Задание 4: предпочтения пользователя с задержкой.
func loadUserTaste(delay time.Duration, ch chan<- string) {
    time.Sleep(delay)
    ch <- "любит фантастику и триллеры"
}

func waitTaste(delay, timeout time.Duration) {
    ch := make(chan string, 1) // буфер: горутина не зависнет после таймаута
    go loadUserTaste(delay, ch)
    select {
    case taste := <-ch:
        fmt.Println("предпочтения:", taste)
    case <-time.After(timeout):
        fmt.Println("предпочтения пользователя пока недоступны")
    }
}

// Задание 5: аналитика — worker pool, мьютекс и context.
type stats struct {
    mu        sync.Mutex
    processed int
}

func (s *stats) inc() {
    s.mu.Lock()
    defer s.mu.Unlock()
    s.processed++
}

func runAnalytics(timeout time.Duration, events []string) {
    ctx, cancel := context.WithTimeout(context.Background(), timeout)
    defer cancel()

    jobs := make(chan string, len(events))
    results := make(chan string, len(events))
    var st stats
    var wg sync.WaitGroup

    for range 2 { // два воркера
        wg.Add(1)
        go func() {
            defer wg.Done()
            for ev := range jobs {
                select {
                case <-ctx.Done():
                    return // время вышло — прекращаем обработку
                case <-time.After(20 * time.Millisecond): // «обработка» события
                    st.inc()
                    results <- "обработано: " + ev
                }
            }
        }()
    }

    for _, ev := range events {
        jobs <- ev
    }
    close(jobs)
    wg.Wait() // после Wait все воркеры закончили — читать st безопасно
    close(results)

    var done []string
    for r := range results {
        done = append(done, r)
    }
    slices.Sort(done)
    for _, r := range done {
        fmt.Println(r)
    }
    if err := ctx.Err(); errors.Is(err, context.DeadlineExceeded) {
        fmt.Println("обработка отменена:", err)
    }
    fmt.Printf("событий обработано: %d из %d\n", st.processed, len(events))
}

func main() {
    // 2
    files := []string{"trailer.mp4", "episode-01.mkv", "teaser.mov"}
    ch := make(chan string)
    for _, f := range files {
        go transcodeVideo(f, ch)
    }
    var statuses []string
    for range files { // ровно столько чтений, сколько отправок — без time.Sleep
        statuses = append(statuses, <-ch)
    }
    slices.Sort(statuses)
    fmt.Println(strings.Join(statuses, "\n"))

    // 3
    events := make(chan string, 4)
    for _, e := range []string{"play", "pause", "seek", "stop"} {
        events <- e
    }
    close(events)
    for e := range events {
        fmt.Println("событие плеера:", e)
    }
    fmt.Println("очередь событий обработана")

    // 4
    waitTaste(10*time.Millisecond, 200*time.Millisecond)
    waitTaste(300*time.Millisecond, 50*time.Millisecond)

    // 5
    analytics := []string{"просмотр начат", "просмотр остановлен", "просмотр завершён",
        "лайк поставлен", "добавлено в избранное"}
    runAnalytics(time.Second, analytics)
    runAnalytics(5*time.Millisecond, analytics)
}
stdout // вывод программы
episode-01.mkv → 1080p готово
teaser.mov → 1080p готово
trailer.mp4 → 1080p готово
событие плеера: play
событие плеера: pause
событие плеера: seek
событие плеера: stop
очередь событий обработана
предпочтения: любит фантастику и триллеры
предпочтения пользователя пока недоступны
обработано: добавлено в избранное
обработано: лайк поставлен
обработано: просмотр завершён
обработано: просмотр начат
обработано: просмотр остановлен
событий обработано: 5 из 5
обработка отменена: context deadline exceeded
событий обработано: 0 из 5

Тренировка: предскажи вывод

go
package main

import "fmt"

func main() {
    ch := make(chan int, 2)
    ch <- 1
    ch <- 2
    close(ch)
    for v := range ch {
        fmt.Print(v, " ")
    }
    v, ok := <-ch
    fmt.Println(v, ok)
}
самопроверкаОтвет
text
1 2 0 false

Закрытый канал отдаёт всё, что успели положить в буфер, и только потом range завершается. Дальнейшее чтение — нулевое значение и false.

Проверь себя

вопросЧем горутина отличается от потока ОС?

Горутина намного легче: стартует со стеком в пару килобайт, который растёт, и переключается планировщиком Go, а не ядром ОС. Тысячи горутин работают на нескольких потоках — модель M:N.

вопросЧто произойдёт с горутинами, когда завершится main?

Программа закончится, и все горутины будут остановлены, даже незаконченные. Их нужно явно дождаться.

вопросКак правильно использовать WaitGroup?

Add(1) до запуска горутины, defer wg.Done() внутри неё, Wait() там, где нужно дождаться. Передавать — по указателю.

вопросЧем небуферизованный канал отличается от буферизованного?

В небуферизованном отправка и получение блокируют друг друга до встречи. В буферизованном отправка не блокируется, пока буфер не полон, а получение — пока он не пуст.

вопросКто закрывает канал и что будет при отправке в закрытый?

Закрывает отправитель. Отправка в закрытый канал — паника; чтение из закрытого и пустого — нулевое значение и ok == false.

вопросЧто делает select, если готовы несколько каналов? А если ни одного?

Выбирает случайный из готовых. Если не готов ни один: с default выполняет его, без default — блокируется.

вопросЗачем нужен worker pool?

Чтобы ограничить число одновременных операций — фиксированное число воркеров обрабатывает задачи из канала — и не перегрузить ресурсы.

вопросЧто такое context и почему cancel вызывают через defer?

Механизм передачи отмены и дедлайна. cancel освобождает ресурсы контекста; если не вызвать — утечка до истечения таймаута или отмены родителя.

вопросКак найти гонку данных?

Запустить программу или тесты с флагом -race.


Ключевые выводы

  • 🪶 Горутины лёгкие: go f(), стек от пары килобайт, планировщик M:N.
  • ⏱️ Ждать горутины нужно явно: WaitGroup или каналы, а не Sleep.
  • 📨 Канал — типизированная труба и точка синхронизации; закрывает только отправитель.
  • 🔀 select ждёт несколько каналов, time.After даёт таймаут, default — неблокирующую проверку.
  • 🔐 Mutex защищает общие данные; гонки ищет флаг -race.
  • 🏭 Worker pool ограничивает параллелизм, context отменяет работу по таймауту или команде.

Chapter goals

  • Start goroutines and wait for them correctly with WaitGroup.
  • Understand unbuffered and buffered channels, close, and range over a channel.
  • Wait for multiple events and timeouts with select.
  • Protect shared data with a mutex and write a worker pool.
  • Cancel work through context.

Goroutines

How does GoFlix load covers, compute recommendations, and stream movies to thousands of users at the same time? Go was built for multithreading, but instead of heavy operating-system threads it has goroutines: lightweight, starting with a small stack of a couple of kilobytes that grows as needed. They are started with the go keyword and managed by the Go scheduler.

The scheduler follows the M:N model: many goroutines are distributed across a smaller number of OS threads, and Go switches between them itself. That is why thousands of goroutines cost almost nothing in memory and keep all CPU cores busy efficiently.

goroutines — thousandsG1G2G3G4P — scheduler contextsone per core (GOMAXPROCS)P1 + goroutine queueP2 + goroutine queueM — OS threadsM1M2

main is a goroutine too

When main finishes, the program ends together with all its goroutines — even the unfinished ones. If main ends too quickly, the goroutines' output may never appear at all.

go
package main

import (
    "fmt"
    "time"
)

func main() {
    go fmt.Println("hello from a goroutine")
    go func() {
        fmt.Println("hello from an anonymous goroutine")
    }()
    time.Sleep(100 * time.Millisecond) // for demonstration only
    fmt.Println("main is done")
    // non-deterministic output: the order of the first two lines may vary
}

Sample output:

text
hello from an anonymous goroutine
hello from a goroutine
main is done

sync.WaitGroup

A WaitGroup is a counter of active goroutines:

  • wg.Add(1) — increment the counter before starting the goroutine;
  • wg.Done() — decrement it when the goroutine finishes; usually via defer;
  • wg.Wait() — block the calling goroutine until the counter reaches zero.
go
package main

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

func main() {
    movies := []string{"Interstellar", "Dune", "Inception"}
    var wg sync.WaitGroup

    for i, movie := range movies {
        wg.Add(1) // before starting the goroutine
        go func() {
            defer wg.Done() // decrements the counter on any exit
            time.Sleep(time.Duration(30*(len(movies)-i)) * time.Millisecond)
            fmt.Println("poster loaded:", movie)
        }()
    }

    wg.Wait() // wait until all goroutines finish
    fmt.Println("all posters loaded")
    // non-deterministic output: whoever finishes earlier prints first
}

Sample output:

text
poster loaded: Inception
poster loaded: Dune
poster loaded: Interstellar
all posters loaded

Goroutines run concurrently, so the messages appear in completion order, not start order. The key part is wg.Wait() after the loop: main moves on only after all the Done calls.

Channels

Go suggests exchanging data through channels — under the motto "Do not communicate by sharing memory; share memory by communicating". A channel is typed: only strings travel through a chan string.

  • Create: ch := make(chan string).
  • Send: ch <- v. Receive: v := <-ch.
  • In an unbuffered channel, a send blocks the goroutine until another one reads the value, and a read blocks until a value is sent. The sender and the receiver meet at a single synchronization point.
go
package main

import "fmt"

func average(ratings []float64) float64 {
    sum := 0.0
    for _, r := range ratings {
        sum += r
    }
    return sum / float64(len(ratings))
}

func main() {
    messages := make(chan string) // unbuffered channel of strings

    go func() {
        messages <- "The Matrix loaded" // the send waits until someone reads
    }()
    fmt.Println(<-messages) // the read waits until someone sends

    avgCh := make(chan float64)
    go func() {
        avgCh <- average([]float64{8.7, 9.0, 8.1})
    }()
    fmt.Printf("average rating: %.2f\n", <-avgCh)
}
stdout // program output
The Matrix loaded
average rating: 8.60

A channel in Go is not just a container — it is a way to safely hand over a value and synchronize goroutines at the same time.

Buffered channels

If the sender does not need to wait for the receiver on every message, the channel is created with a buffer: make(chan T, N). A send blocks only when the buffer is full, a read — when it is empty. Essentially it is a small queue: the sender can "run ahead". Convenient when messages arrive in bursts.

go
package main

import "fmt"

func main() {
    notifications := make(chan string, 3)
    notifications <- "New movie: Dune 2"
    notifications <- "50% off!"
    notifications <- "New season: The Mandalorian"
    // notifications <- "one more" — would block: the buffer is full

    fmt.Println(len(notifications), "of", cap(notifications), "queued")
    fmt.Println(<-notifications)
    fmt.Println(<-notifications)
    fmt.Println(len(notifications), "queued")
}
stdout // program output
3 of 3 queued
New movie: Dune 2
50% off!
1 queued

close and range over a channel

close(ch) tells receivers: there will be no more values.

  • The loop for v := range ch reads while the channel is open and non-empty, then finishes by itself. Closing does not discard already sent values.
  • Reading from a closed, empty channel returns the zero value and ok == false.
  • Sending to a closed channel panics: send on closed channel.
  • Only the sender closes the channel — never the receiver.
go
package main

import "fmt"

func main() {
    moviesCh := make(chan string)
    go func() {
        defer close(moviesCh) // closed by the sender: "no more data"
        for _, m := range []string{"The Matrix", "Inception", "Tenet"} {
            moviesCh <- m
        }
    }()
    for movie := range moviesCh { // the loop ends after close
        fmt.Println("received:", movie)
    }

    done := make(chan int)
    close(done)
    val, ok := <-done // closed and empty: zero value and false
    fmt.Println("value:", val, "open?", ok)
}
stdout // program output
received: The Matrix
received: Inception
received: Tenet
value: 0 open? false
go
package main

func main() {
    ch := make(chan int, 1)
    close(ch)
    ch <- 1 // panic expected
}
text
panic: send on closed channel

If there are several senders, the channel may be closed only when all of them are done sending — that is what WaitGroup plus a separate goroutine that closes the channel after wg.Wait() are for:

go
package main

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

func main() {
    results := make(chan string)
    var wg sync.WaitGroup
    for _, film := range []string{"Dune", "The Matrix", "Inception"} {
        wg.Add(1)
        go func() {
            defer wg.Done()
            results <- film + ": cover ready"
        }()
    }
    go func() {
        wg.Wait()      // all senders are done
        close(results) // now closing is safe
    }()

    var all []string
    for r := range results {
        all = append(all, r)
    }
    slices.Sort(all) // goroutines finish in any order
    fmt.Println(all)
}
stdout // program output
[Dune: cover ready Inception: cover ready The Matrix: cover ready]

Signal channel

When there is no data to pass and only the fact of an event matters — "the work is done", "time to stop" — a channel of empty structs chan struct{} is used. The signal is a send of struct{}{} or a close of the channel. Closing is handier: all waiting goroutines "hear" it at once.

go
package main

import (
    "fmt"
    "time"
)

func main() {
    done := make(chan struct{}) // no data — only the signal matters
    go func() {
        fmt.Println("goroutine working...")
        time.Sleep(50 * time.Millisecond)
        close(done) // a signal to everyone waiting
    }()
    <-done
    fmt.Println("main: received the completion signal")
}
stdout // program output
goroutine working...
main: received the completion signal

select

select looks like switch, but for channels: it waits until one of the channels is ready and runs its case.

  • Several are ready — a random one is chosen.
  • None is ready and there is no default — select blocks.
  • default makes select non-blocking: if there is no data, move on immediately.
  • time.After(d) — a channel that receives a value after d: this is how waits are bounded in time.
go
package main

import (
    "fmt"
    "time"
)

func fetch(delay time.Duration, movie string) <-chan string {
    ch := make(chan string, 1) // buffer 1: the goroutine won't hang if the result is never read
    go func() {
        time.Sleep(delay)
        ch <- movie
    }()
    return ch
}

func main() {
    select {
    case movie := <-fetch(50*time.Millisecond, "Interstellar"):
        fmt.Println("recommendation:", movie)
    case <-time.After(200 * time.Millisecond):
        fmt.Println("timeout: the recommendations service did not respond")
    }

    select {
    case movie := <-fetch(300*time.Millisecond, "Dune"):
        fmt.Println("recommendation:", movie)
    case <-time.After(100 * time.Millisecond):
        fmt.Println("timeout: the recommendations service did not respond")
    }

    empty := make(chan string)
    select {
    case msg := <-empty:
        fmt.Println(msg)
    default:
        fmt.Println("no data — moving on") // default makes select non-blocking
    }
}
stdout // program output
recommendation: Interstellar
timeout: the recommendations service did not respond
no data — moving on

select without default — when you truly need to wait for one of the events; with default — when you need to check the channels without waiting.

sync.Mutex

Sometimes it is more convenient not to pass data around but to protect a shared resource. A sync.Mutex (mutual exclusion) guarantees that only one goroutine works with the resource while the others wait. Lock() — enter the critical section, Unlock() — leave it; defer Unlock() right after Lock() releases the mutex on any exit, even during a panic.

go
package main

import (
    "fmt"
    "sync"
)

// ViewCounter — a thread-safe view counter.
type ViewCounter struct {
    mu    sync.Mutex
    count int
}

func (vc *ViewCounter) Increment() {
    vc.mu.Lock()
    defer vc.mu.Unlock() // released on any exit
    vc.count++
}

func (vc *ViewCounter) Value() int {
    vc.mu.Lock()
    defer vc.mu.Unlock()
    return vc.count
}

func main() {
    counter := &ViewCounter{}
    var wg sync.WaitGroup
    for range 1000 {
        wg.Add(1)
        go func() {
            defer wg.Done()
            counter.Increment()
        }()
    }
    wg.Wait()
    fmt.Println("views:", counter.Value())
}
stdout // program output
views: 1000

Even the read is protected by the mutex, to get a consistent value. Without the mutex, several goroutines would read and mutate the same field at once — this is a data race, and the total could come out below 1000.

Worker pool

There are many tasks, but starting a goroutine for each one is a bad idea: you can overload the database or an external service. A worker pool is a fixed number of worker goroutines that take tasks from a jobs channel and put results into results. After all tasks are sent, the jobs channel is closed: once it drains, each worker's range loop ends. The pattern limits the number of simultaneous operations and makes resource control simple.

go
package main

import (
    "fmt"
    "time"
)

// worker processes tasks from jobs until the channel is closed and empty.
func worker(id int, jobs <-chan string, results chan<- string) {
    for film := range jobs {
        time.Sleep(10 * time.Millisecond) // "processing"
        results <- fmt.Sprintf("worker %d processed: %s", id, film)
    }
}

func main() {
    films := []string{"Dune", "The Matrix", "Tenet", "Inception", "Avatar"}
    jobs := make(chan string, len(films))
    results := make(chan string, len(films))

    for w := 1; w <= 3; w++ { // exactly three workers, no matter how many tasks
        go worker(w, jobs, results)
    }

    for _, f := range films {
        jobs <- f
    }
    close(jobs) // signal: no more tasks

    for range films { // as many reads as there are tasks
        fmt.Println(<-results)
    }
    // non-deterministic output: which worker takes what is up to the scheduler
}

Sample output:

text
worker 3 processed: Dune
worker 1 processed: The Matrix
worker 2 processed: Tenet
worker 2 processed: Avatar
worker 3 processed: Inception

The order of results differs every run: whichever worker finishes first sends its result first. The types <-chan string and chan<- string are read-only and write-only channels: the compiler will not let a worker accidentally write into jobs.

context: cancellation and deadlines

In real services, work has to be cancelled: the user left, a timeout expired, the request was aborted. The context package carries the cancellation signal and the deadline.

Function When the context is cancelled
context.WithCancel(parent) when cancel() is called or the parent is cancelled
context.WithTimeout(parent, d) after the duration d
context.WithDeadline(parent, t) at the moment t

ctx.Done() returns a channel that closes on cancellation; ctx.Err() explains the reason: context canceled or context deadline exceeded. The cancel function must always be called, usually via defer — it releases the context's resources.

go
package main

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

func slowRecommendations(ctx context.Context, delay time.Duration) (string, error) {
    select {
    case <-time.After(delay): // "slow" work
        return "Interstellar, Dune", nil
    case <-ctx.Done(): // cancellation or deadline
        return "", ctx.Err()
    }
}

func main() {
    ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
    defer cancel() // release the context's resources in any case

    res, err := slowRecommendations(ctx, 50*time.Millisecond)
    fmt.Println("made it:", res, err)

    res, err = slowRecommendations(ctx, 300*time.Millisecond)
    fmt.Printf("missed it: %q, %v\n", res, err)

    ctx2, cancel2 := context.WithCancel(context.Background())
    var wg sync.WaitGroup
    wg.Add(1)
    go func() {
        defer wg.Done()
        for {
            select {
            case <-ctx2.Done():
                fmt.Println("streaming stopped:", ctx2.Err())
                return
            default:
                time.Sleep(20 * time.Millisecond) // "stream" a chunk of the movie
            }
        }
    }()
    time.Sleep(70 * time.Millisecond)
    cancel2() // manual cancellation — the goroutine will finish
    wg.Wait()
}
stdout // program output
made it: Interstellar, Dune <nil>
missed it: "", context deadline exceeded
streaming stopped: context canceled

context does not merely wait for a task to finish — it manages its lifecycle: stops it on a timeout, on a deadline, or on command. On the backend, the context is passed as the first parameter into every function that talks to the network or the database — see 19 — Working with databases → Context throughout the application.

Summary

Tool What for Key details
Goroutine a lightweight concurrent function go f(), stack from a couple of KB, M:N scheduler
sync.WaitGroup wait for a group of goroutines Add before the start, defer Done, Wait until zero
Channel safe data exchange unbuffered — a rendezvous; buffered — a queue
close and range the end of a data stream the sender closes; writing to a closed one panics
select wait on several channels a random one of the ready; default — without waiting
sync.Mutex protect shared data Lock + defer Unlock
Worker pool limit parallelism N workers read jobs, write results
context cancellation and deadlines WithCancel, WithTimeout, Done(), Err()

Practice

Homework

  1. Parallel episode checks. The function checkEpisode(title string, delay int, wg *sync.WaitGroup) simulates a check with time.Sleep and reports that the episode is ready to publish. Start a goroutine per episode, wait for all of them with a WaitGroup, and print that all episodes are checked.
  2. Transcoding statuses through a channel. The function transcodeVideo(name string, ch chan string) simulates transcoding and sends a result string into the channel. Start a goroutine per file, collect the results from the channel, and print them. No time.Sleep for waiting.
  3. Player event queue. A buffered channel of strings, the events play, pause, seek, stop. Send them all, close the channel, read it with a for range loop, and at the end report that the queue is processed.
  4. Preferences with a timeout. loadUserTaste sends a description of the user's preferences into a channel after a delay. With select, either receive the result or, on a timeout, report that preferences are unavailable for now.
  5. Mini analytics. Events: playback started, playback stopped, playback finished, like added, added to favorites. A jobs channel, a results channel, several workers; close jobs after sending, collect the results, wait for the workers with a WaitGroup; count the processed events under a mutex; add context.WithTimeout and, if time runs out, stop processing and report the cancellation.
solution

Task 1 — the order in which episodes finish depends on the delays and the scheduler:

go
package main

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

func checkEpisode(title string, delay int, wg *sync.WaitGroup) {
    defer wg.Done()
    time.Sleep(time.Duration(delay) * time.Millisecond) // simulating a check
    fmt.Printf("episode %q is ready to publish\n", title)
}

func main() {
    episodes := map[string]int{"Pilot": 30, "Episode 2": 10, "Finale": 20}
    var wg sync.WaitGroup
    for title, delay := range episodes {
        wg.Add(1)
        go checkEpisode(title, delay, &wg)
    }
    wg.Wait()
    fmt.Println("all episodes checked successfully")
    // non-deterministic output: episodes finish in a different order
}

Sample output:

text
episode "Episode 2" is ready to publish
episode "Finale" is ready to publish
episode "Pilot" is ready to publish
all episodes checked successfully

Tasks 2–5:

go
package main

import (
    "context"
    "errors"
    "fmt"
    "slices"
    "strings"
    "sync"
    "time"
)

// Task 2: transcoding, results through a channel.
func transcodeVideo(name string, ch chan<- string) {
    time.Sleep(time.Duration(len(name)) * time.Millisecond) // simulating work
    ch <- name + " → 1080p ready"
}

// Task 4: user preferences with a delay.
func loadUserTaste(delay time.Duration, ch chan<- string) {
    time.Sleep(delay)
    ch <- "loves sci-fi and thrillers"
}

func waitTaste(delay, timeout time.Duration) {
    ch := make(chan string, 1) // buffer: the goroutine won't hang after a timeout
    go loadUserTaste(delay, ch)
    select {
    case taste := <-ch:
        fmt.Println("preferences:", taste)
    case <-time.After(timeout):
        fmt.Println("user preferences unavailable for now")
    }
}

// Task 5: analytics — worker pool, mutex, and context.
type stats struct {
    mu        sync.Mutex
    processed int
}

func (s *stats) inc() {
    s.mu.Lock()
    defer s.mu.Unlock()
    s.processed++
}

func runAnalytics(timeout time.Duration, events []string) {
    ctx, cancel := context.WithTimeout(context.Background(), timeout)
    defer cancel()

    jobs := make(chan string, len(events))
    results := make(chan string, len(events))
    var st stats
    var wg sync.WaitGroup

    for range 2 { // two workers
        wg.Add(1)
        go func() {
            defer wg.Done()
            for ev := range jobs {
                select {
                case <-ctx.Done():
                    return // time is up — stop processing
                case <-time.After(20 * time.Millisecond): // "processing" an event
                    st.inc()
                    results <- "processed: " + ev
                }
            }
        }()
    }

    for _, ev := range events {
        jobs <- ev
    }
    close(jobs)
    wg.Wait() // after Wait all workers are done — reading st is safe
    close(results)

    var done []string
    for r := range results {
        done = append(done, r)
    }
    slices.Sort(done)
    for _, r := range done {
        fmt.Println(r)
    }
    if err := ctx.Err(); errors.Is(err, context.DeadlineExceeded) {
        fmt.Println("processing cancelled:", err)
    }
    fmt.Printf("events processed: %d of %d\n", st.processed, len(events))
}

func main() {
    // 2
    files := []string{"trailer.mp4", "episode-01.mkv", "teaser.mov"}
    ch := make(chan string)
    for _, f := range files {
        go transcodeVideo(f, ch)
    }
    var statuses []string
    for range files { // exactly as many reads as sends — no time.Sleep
        statuses = append(statuses, <-ch)
    }
    slices.Sort(statuses)
    fmt.Println(strings.Join(statuses, "\n"))

    // 3
    events := make(chan string, 4)
    for _, e := range []string{"play", "pause", "seek", "stop"} {
        events <- e
    }
    close(events)
    for e := range events {
        fmt.Println("player event:", e)
    }
    fmt.Println("event queue processed")

    // 4
    waitTaste(10*time.Millisecond, 200*time.Millisecond)
    waitTaste(300*time.Millisecond, 50*time.Millisecond)

    // 5
    analytics := []string{"playback started", "playback stopped", "playback finished",
        "like added", "added to favorites"}
    runAnalytics(time.Second, analytics)
    runAnalytics(5*time.Millisecond, analytics)
}
stdout // program output
episode-01.mkv → 1080p ready
teaser.mov → 1080p ready
trailer.mp4 → 1080p ready
player event: play
player event: pause
player event: seek
player event: stop
event queue processed
preferences: loves sci-fi and thrillers
user preferences unavailable for now
processed: added to favorites
processed: like added
processed: playback finished
processed: playback started
processed: playback stopped
events processed: 5 of 5
processing cancelled: context deadline exceeded
events processed: 0 of 5

Exercise: predict the output

go
package main

import "fmt"

func main() {
    ch := make(chan int, 2)
    ch <- 1
    ch <- 2
    close(ch)
    for v := range ch {
        fmt.Print(v, " ")
    }
    v, ok := <-ch
    fmt.Println(v, ok)
}
self-check
text
1 2 0 false

A closed channel hands over everything that made it into the buffer, and only then does range end. Any further read gives the zero value and false.

Check yourself

questionHow does a goroutine differ from an OS thread?

A goroutine is much lighter: it starts with a stack of a couple of kilobytes that grows, and the Go scheduler — not the OS kernel — switches it. Thousands of goroutines run on a few threads — the M:N model.

questionWhat happens to goroutines when main finishes?

The program ends and all goroutines are stopped, even the unfinished ones. You must wait for them explicitly.

questionHow do you use a WaitGroup correctly?

Add(1) before starting the goroutine, defer wg.Done() inside it, Wait() where you need to wait. Pass it by pointer.

questionHow does an unbuffered channel differ from a buffered one?

In an unbuffered one, send and receive block each other until they meet. In a buffered one, the send does not block until the buffer is full, and the receive — until it is empty.

questionWho closes the channel, and what happens if you send to a closed one?

The sender closes. Sending to a closed channel panics; reading from a closed, empty one gives the zero value and ok == false.

questionWhat does select do when several channels are ready? And when none is?

It picks a random one of the ready. When none is ready: with default it runs that; without default it blocks.

questionWhy do you need a worker pool?

To limit the number of simultaneous operations — a fixed set of workers processes tasks from a channel — and to avoid overloading resources.

questionWhat is context, and why is cancel called via defer?

A mechanism for carrying cancellation and deadlines. cancel releases the context's resources; skipping it leaks them until the timeout expires or the parent is cancelled.

questionHow do you find a data race?

Run the program or the tests with the -race flag.


Key takeaways

  • 🪶 Goroutines are lightweight: go f(), a stack of a couple of kilobytes, an M:N scheduler.
  • ⏱️ Goroutines must be waited for explicitly: a WaitGroup or channels, not Sleep.
  • 📨 A channel is a typed pipe and a synchronization point; only the sender closes it.
  • 🔀 select waits on several channels, time.After provides a timeout, default — a non-blocking check.
  • 🔐 A Mutex protects shared data; the -race flag finds races.
  • 🏭 A worker pool limits parallelism; context cancels work on a timeout or on command.
// related topics and cheatsheets