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.
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:
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")
}
main is doneWhen 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.
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")
}
reminder sent for 1044
reminder sent for 1042
reminder sent for 1043
all reminders sentThe 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.
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))
}
one after another: 300ms
at the same time: 100ms100 * 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.
Coming from 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 withwg.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.