Skip to content

Run Work on Goroutines

The Course
•
24 min study

A goroutine is a function running independently of the code that started it. You start one by writing go before a function call, and the call returns immediately while the function carries on by itself. Goroutines are cheap, so a Go program can easily run thousands. The hard part is not starting them; it is knowing when they have finished and getting their results back without two goroutines touching the same data at once.

Go's main tool for that is the channel. A channel carries values of one type from one goroutine to another. On an unbuffered channel, made with make(chan T), a send waits until another goroutine receives, so every send is also a moment where the two goroutines meet. Closing a channel says "no more values", and a for ... range over a channel stops when it is closed and empty.

One thread in the browser

The browser editor runs Go on a single thread. Goroutines still take turns, channels and locks still work, and every program in this course prints the same output in the browser as with a local Go install. What the browser cannot show is goroutines running at the same instant, so it cannot reveal a data race. The project's download runs go test -race for that.

Predict and run

One goroutine produces values and closes the channel. main receives them. In what order are the lines printed?

Predict, then run Go
package main

import (
	"fmt"
	"strings"
)

func produce(items []string, out chan<- string) {
	for _, item := range items {
		out <- strings.ToUpper(item)
	}
	close(out)
}

func main() {
	results := make(chan string)
	go produce([]string{"tent", "drill", "lamp"}, results)
	for item := range results {
		fmt.Println("received", item)
	}
	fmt.Println("channel closed")
}
Check your prediction
Text
received TENT
received DRILL
received LAMP
channel closed

With one sender and one receiver, the values arrive in the order they were sent. chan<- string in produce's signature means "send only": the compiler stops produce from receiving by mistake. Remove close(out) and run again. main waits forever for a fourth value, and Go reports all goroutines are asleep - deadlock!.

Wait for several goroutines

When several goroutines work at once, a sync.WaitGroup counts them. Call Add(1) before starting each one, Done() when it finishes, usually with defer, and Wait() to block until the count is back to zero. Giving each goroutine its own slot in a results slice means no two of them write the same memory, and reading the slice after Wait is safe.

Each goroutine writes its own slot Go
package main

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

func main() {
	items := []string{"tent", "drill", "lamp", "hat"}
	lengths := make([]int, len(items))
	var wg sync.WaitGroup
	for i, item := range items {
		wg.Add(1)
		go func() {
			defer wg.Done()
			lengths[i] = len(strings.TrimSpace(item))
		}()
	}
	wg.Wait()
	fmt.Println(lengths)
}
Text
[4 5 4 3]

The goroutines may finish in any order, but the output is always the same, because each result goes to the index of its input. Since Go 1.22, i and item are new variables in every iteration, so each closure sees its own pair, just as on Day 1.

Shared data needs a lock

If several goroutines update the same variable, such as a shared counter, their reads and writes can interleave and lose updates. That is a data race, and its results vary from run to run. A sync.Mutex makes each update happen alone: Lock waits until no other goroutine holds the lock, and Unlock releases it.

A counter guarded by a mutex Go
package main

import (
	"fmt"
	"sync"
)

type Counter struct {
	mu    sync.Mutex
	total int
}

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

func main() {
	var c Counter
	var wg sync.WaitGroup
	for range 100 {
		wg.Add(1)
		go func() {
			defer wg.Done()
			c.Add(2)
		}()
	}
	wg.Wait()
	fmt.Println("Total:", c.total)
}
Text
Total: 200

Counter has pointer methods, and it must not be copied after use, because a copied mutex is a separate lock. go vet reports such copies. To see the race detector catch a mistake, save this program as main.go in a folder of its own, run go mod init race there, and delete the Lock and Unlock lines. Then run go run -race .. It reports WARNING: DATA RACE, with the read and the earlier write in Add that conflicted, and the program exits with an error status, even when the total happens to come out right. Use go run -race for a program like this one. go test -race runs a package's tests, so in a folder with no _test.go files it reports no test files and checks nothing.

Practice

Exercise

Your turn

Split the quantities 3, 8, 1, 9, 4, 6, 2 into chunks of 3, sum each chunk on its own goroutine, and store each sum in its own slot. Print the chunk sums and the total. Make sure the last, shorter chunk is included.

The output should be:

Text
[12 19 2] 33
Your working space Go
package main

func main() {
	quantities := []int{3, 8, 1, 9, 4, 6, 2}
	_ = quantities
	// Sum each chunk of 3 on its own goroutine.
}
Hint 1: the idea

Work out the number of chunks first, so you can make the results slice before starting any goroutine.

Hint 2: a first step

With chunk := 3, there are (len(quantities) + chunk - 1) / chunk chunks. Chunk c covers quantities[c*chunk : min((c+1)*chunk, len(quantities))].

Worked solution
Run the solution Go
package main

import (
	"fmt"
	"sync"
)

func main() {
	quantities := []int{3, 8, 1, 9, 4, 6, 2}
	const chunk = 3
	sums := make([]int, (len(quantities)+chunk-1)/chunk)
	var wg sync.WaitGroup
	for c := range sums {
		part := quantities[c*chunk : min((c+1)*chunk, len(quantities))]
		wg.Add(1)
		go func() {
			defer wg.Done()
			for _, q := range part {
				sums[c] += q
			}
		}()
	}
	wg.Wait()
	total := 0
	for _, s := range sums {
		total += s
	}
	fmt.Println(sums, total)
}
Text
[12 19 2] 33

There are three chunks, and the last one holds only the 2. Each goroutine writes only sums[c] for its own c, so there is no race, and total is computed after Wait, when every sum is complete.

Was this article helpful?

Your response is saved on this device.