Go Playbook

Course › Week 4 · Concurrency and plugging into Laravel › Day 1 · lesson 22 of 42 · 20 min reading + 60 min practice

Goroutines and WaitGroup

Run work at the same time with go, and wait for all of it with a WaitGroup.

goroutinesgosync.WaitGroupsync.Mutex

On this page
  1. Starting goroutines
  2. Sharing data
  3. Coming from PHP
  4. Practice
  5. Remember

A PHP request runs one thing at a time. To do three slow things at once, a Laravel app queues three jobs and runs three workers. In Go you write go in front of a function call, and it runs at the same time as the rest of the program, in the same process. That is a goroutine.

Goroutines are cheap: a program can run thousands of them. Today: starting them, waiting for them, measuring the time it saves, and the bug that appears the moment two goroutines touch the same variable.

Starting goroutines

1. go starts a goroutine, and main does not wait

go sendReminder(id) starts the call and moves on at once. Here main reaches its end before any reminder is sent:

main.go
package main

import "fmt"

func sendReminder(bookingID int) {
	fmt.Println("reminder sent for", bookingID)
}

func main() {
	for _, id := range []int{1042, 1043, 1044} {
		go sendReminder(id)
	}
	fmt.Println("main is done")
}
$ go run .
main is done

When main returns, the program ends, and every goroutine still running is stopped mid-way. A goroutine nobody waits for is work that may or may not happen, which in production means reminders that are sometimes not sent.

2. sync.WaitGroup waits for all of them

A sync.WaitGroup tracks a group of goroutines. wg.Go(f) starts f in a goroutine of the group, and wg.Wait() blocks until every one of them has returned.

main.go
package main

import (
	"fmt"
	"sync"
)

func sendReminder(bookingID int) {
	fmt.Println("reminder sent for", bookingID)
}

func main() {
	var wg sync.WaitGroup
	for _, id := range []int{1042, 1043, 1044} {
		wg.Go(func() {
			sendReminder(id)
		})
	}
	wg.Wait()
	fmt.Println("all reminders sent")
}
$ go run .
reminder sent for 1044
reminder sent for 1042
reminder sent for 1043
all reminders sent

The three lines came out in an order nobody chose: the goroutines run independently, and each run of the program may print them differently. id is safe to use inside the closure because each loop round has its own variable (the closures lesson).

wg.Go is new in Go 1.25. Older code does the same with three calls, and you will see it everywhere: wg.Add(1) before starting, go func() { defer wg.Done(); … }(), and wg.Wait(). Forgetting the Add or the Done is a classic bug that wg.Go makes impossible.

3. Measuring the time it saves

Three calls of 100 ms each, one after another, then at the same time. time.Now() is the current time, and time.Since(start) the time passed since then, a time.Duration.

main.go
package main

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

// fetchRates stands in for a call to a channel manager's API that takes about 100 ms.
func fetchRates(property string) {
	time.Sleep(100 * time.Millisecond)
}

func main() {
	properties := []string{"nyhavn", "vesterbro", "amager"}

	start := time.Now()
	for _, p := range properties {
		fetchRates(p)
	}
	fmt.Println("one after another:", time.Since(start).Round(10*time.Millisecond))

	start = time.Now()
	var wg sync.WaitGroup
	for _, p := range properties {
		wg.Go(func() { fetchRates(p) })
	}
	wg.Wait()
	fmt.Println("at the same time: ", time.Since(start).Round(10*time.Millisecond))
}
$ go run .
one after another: 300ms
at the same time:  100ms

100 * time.Millisecond is a time.Duration; durations print as 300ms, 1.5s. Round drops the microseconds that would change on every run.

Waiting is what goroutines are best at: while one waits for a network answer, a database or a disk, the others run. Three waits of 100 ms at the same time take 100 ms, on any number of cores. That is the kind of work Week 4 is about.

Sharing data

4. A data race

Four goroutines add to the same counter, a million times each. The answer should be 4,000,000:

main.go
package main

import (
	"fmt"
	"sync"
)

func main() {
	processed := 0

	var wg sync.WaitGroup
	for range 4 {
		wg.Go(func() {
			for range 1_000_000 {
				processed++
			}
		})
	}
	wg.Wait()

	fmt.Println("processed:", processed)
}
$ go run .
processed: 3507113

for range 4 runs four times without a loop variable, and 1_000_000 is a million, written with underscores for reading.

processed++ is three steps: read the value, add one, write it back. When two goroutines read the same value at the same time, both write back the same result, and one addition is lost. That is a data race, and the total changes on every run. It compiles, go vet and staticcheck are quiet, and on a fast test it may even look right. The errgroup lesson shows the tool that finds it.

5. sync.Mutex

A sync.Mutex lets one goroutine at a time into a piece of code. Lock waits until no one else holds it; Unlock lets the next one in.

main.go
package main

import (
	"fmt"
	"sync"
)

// Counter is safe to use from many goroutines at once.
type Counter struct {
	mu    sync.Mutex
	value int
}

func (c *Counter) Add(n int) {
	c.mu.Lock()
	defer c.mu.Unlock()
	c.value += n
}

func (c *Counter) Value() int {
	c.mu.Lock()
	defer c.mu.Unlock()
	return c.value
}

func main() {
	var processed Counter

	var wg sync.WaitGroup
	for range 4 {
		wg.Go(func() {
			for range 1_000_000 {
				processed.Add(1)
			}
		})
	}
	wg.Wait()

	fmt.Println("processed:", processed.Value())
}
$ go run .
processed: 4000000

The mutex lives next to the data it protects, both unexported, and every method locks it. defer c.mu.Unlock() unlocks whatever way the method returns, the same habit as defer file.Close().

The methods have pointer receivers, and the counter is never copied: a copied mutex is a second, unrelated lock. go vet reports a copied sync.Mutex when it sees one.

6. Better: each goroutine writes its own slot

The simplest safe design shares nothing that changes. Give each goroutine its own element of a slice, made with the final length up front, and read the slice only after Wait.

main.go
package main

import (
	"fmt"
	"strings"
	"sync"
)

// wordCount stands in for slow work on one comment.
func wordCount(comment string) int {
	return len(strings.Fields(comment))
}

func main() {
	comments := []string{"Clear explanations, thank you", "Too fast", "The homework was useful"}

	counts := make([]int, len(comments))
	var wg sync.WaitGroup
	for i, comment := range comments {
		wg.Go(func() {
			counts[i] = wordCount(comment)
		})
	}
	wg.Wait()

	fmt.Println(counts)
}
$ go run .
[4 2 4]

strings.Fields splits on whitespace. Every goroutine writes to a different index, so no two touch the same memory, and the results come out in the input’s order however the goroutines were scheduled. wg.Wait() also guarantees that main sees every write.

Writing to different elements of a slice is safe; append to a shared slice is not, and neither is writing to a shared map: a map written from two goroutines can crash the program.

Coming from PHP

SendReminders.php
<?php
// One request, one thing at a time:
foreach ($bookingIds as $id) {
    $this->reminders->send($id);          // 3 × 100 ms = 300 ms
}

// At the same time, Laravel's way: separate processes.
Bus::batch(array_map(fn ($id) => new SendReminder($id), $bookingIds))->dispatch();
$results = Concurrency::run([fn () => $a->fetch(), fn () => $b->fetch()]);

Laravel gets concurrency from processes: queue workers, Concurrency::run with forked child processes, or Http::pool for parallel HTTP. Each process has its own memory, so there are no data races, and each costs tens of megabytes and the time to start.

Goroutines share one process and its memory. That makes them cheap (a few kilobytes each) and fast to start, and it is exactly why the data race exists. In Go, sharing is the default and safety is your design.

PracticeA Tour of Go: goroutines and sync.Mutex; Learn Go with Tests: Concurrency

In A Tour of Go, do Goroutines and sync.Mutex. Then Concurrency in Learn Go with Tests: it speeds up a website checker with goroutines, and uses channels, which are next.

Exercise: fetch three rates

Change fetchRates from section 3 to return a price in cents for each property (any number), and collect the three prices into a slice in the input’s order, using one slot per goroutine. Print the total and how long it took. Then make one property’s call take 300 ms instead of 100: what is the total time now, and why?

Remember

  • Every goroutine has someone waiting for it: start with wg.Go, end with wg.Wait.
  • Two goroutines never touch the same variable without a sync.Mutex; better, give each its own slot of a pre-sized slice.

Tomorrow: channels, to send values between goroutines, and select, to wait on several at once.