Go Goroutines
Concurrency is where Go really stands out. A goroutine is a function running independently, at the same time as other goroutines. You start one by putting the keyword go in front of a function call. That's all.
Goroutines are not operating-system threads. They are managed by the Go runtime, start with a tiny stack of a few kilobytes that grows as needed, and are multiplexed onto a handful of real threads. A program can comfortably run hundreds of thousands of goroutines.
| OS thread | Goroutine | |
|---|---|---|
| Initial memory | ~1–8 MB stack | ~2–8 KB stack, grows on demand |
| Created by | the operating system | the Go runtime |
| Cost to start | relatively high | very low |
| Typical count | dozens to thousands | thousands to millions |
Starting a goroutine
go doWork() // run a named function concurrently
go func() { ... }() // run an anonymous function concurrentlyThe go statement returns immediately; the caller does not wait. And when main returns, the whole program exits — including all goroutines that are still running. So this program prints only one line:
package main
import (
"fmt"
"time"
)
func slowSay(msg string) {
time.Sleep(500 * time.Millisecond) // pretend to do slow work
fmt.Println(msg)
}
func main() {
go slowSay("from the goroutine") // never gets to print
fmt.Println("main is done")
}main is done
The goroutine was started, but main finished first and took it down. We need a way to wait.
Waiting with a channel
The simplest way to wait for a goroutine is to have it send a value on a channel when it is done (channels get their own chapter soon). Receiving from the channel blocks until the value arrives.
package main
import "fmt"
func sumTo(n int, result chan int) {
total := 0
for i := 1; i <= n; i++ {
total += i
}
result <- total // send the answer back
}
func main() {
result := make(chan int)
go sumTo(1_000_000, result)
fmt.Println("main keeps working while the goroutine computes...")
fmt.Println("sum:", <-result) // wait for the answer
}main keeps working while the goroutine computes...
sum: 500000500000
Many goroutines, deterministic output
Goroutines run in an unpredictable order, so printing from inside them gives jumbled output that changes from run to run. A reliable pattern: give each goroutine its own slot in a results slice, wait for all of them, then print in order.
package main
import (
"fmt"
"strings"
"sync"
)
func main() {
words := []string{"gopher", "channel", "select", "mutex"}
results := make([]string, len(words))
var wg sync.WaitGroup
for i, w := range words {
wg.Add(1)
go func() {
defer wg.Done()
results[i] = strings.ToUpper(w) // each goroutine writes only its own index
}()
}
wg.Wait() // block until every goroutine has called Done
for i, r := range results {
fmt.Println(i, r)
}
}0 GOPHER
1 CHANNEL
2 SELECT
3 MUTEX
The sync.WaitGroup counts running goroutines — it is explained in detail in the next chapter. Because each goroutine writes a different index, they never touch the same memory and need no further synchronisation.
Note: Since Go 1.22, each loop iteration has its own
iandw, so capturing them in the closure is safe. In older Go versions you had to pass them as arguments:go func(i int, w string) { ... }(i, w).
Concurrency is not parallelism
Concurrency is about structuring a program as independent tasks. Parallelism is about executing tasks at literally the same moment on multiple CPU cores. Go programs are written concurrently; the runtime runs them in parallel when cores are available (runtime.NumCPU() of them by default).
package main
import (
"fmt"
"sync"
)
func isPrime(n int) bool {
if n < 2 {
return false
}
for d := 2; d*d <= n; d++ {
if n%d == 0 {
return false
}
}
return true
}
func countPrimes(lo, hi int) int {
count := 0
for n := lo; n < hi; n++ {
if isPrime(n) {
count++
}
}
return count
}
func main() {
const chunks = 4
const limit = 200_000
counts := make([]int, chunks)
var wg sync.WaitGroup
for c := range chunks {
wg.Add(1)
go func() {
defer wg.Done()
size := limit / chunks
counts[c] = countPrimes(c*size, (c+1)*size)
}()
}
wg.Wait()
total := 0
for c, n := range counts {
fmt.Printf("chunk %d: %d primes\n", c, n)
total += n
}
fmt.Println("total primes below", limit, "=", total)
}chunk 0: 5133 primes
chunk 1: 4459 primes
chunk 2: 4256 primes
chunk 3: 4136 primes
total primes below 200000 = 17984
The four chunks are searched concurrently, but the output is always identical because it is printed after Wait, in index order.
Data races
If two goroutines access the same variable at the same time and at least one of them writes, you have a data race — results become unpredictable. Run your tests with go test -race (or go run -race) to detect races. The tools to avoid them are channels and mutexes, covered in the next chapters.
Test yourself
How do you start a goroutine?
thread f()go f()async f()spawn(f)
What happens to running goroutines when main returns?
- They keep running
- Main waits for them automatically
- They are stopped as the program exits
- They become zombies
Why is printing from many goroutines non-deterministic?
fmtis broken- Goroutines are scheduled in an unpredictable order
- Goroutines run in reverse order
- Output is buffered randomly