Lesson contents

Go — Goroutines and channel ownership

Use a channel to pass readings from a producer goroutine to a consumer and signal completion.

A simple example

Pass one number through a channel

  1. Start with A goroutine sends 2
  2. Do this Receive on the channel
  3. Result 2
The receive waits for the send. The main program then prints the number it received.
main.go
package main

import "fmt"


func main() {
    numbers := make(chan int)
    go func() { numbers <- 2 }()
    fmt.Println(<-numbers)
}
Output
2
Advertisements

Collect results from a goroutine

An unbuffered channel synchronizes each send with a receive. The producer owns the close, and the consumer ranges until the channel closes. Leaving the producer open would keep the consumer waiting.

First count: 4 visitors. Second count: 7 visitors. Combined: 11 visitors.
Collect two gate counts

A worker sends visitor counts of 4 and 7 to the main program. The main program totals each count as it arrives. Closing the channel tells the receiver that the final total is eleven.

Run the example

Go 1.20 or later. Run these commands from the directory containing the example.

go run main.go
main.go
package main

import (
	"fmt"
)

func main() {
	readings := make(chan int)
	go func() {
		defer close(readings)
		for _, n := range []int{4, 7} {
			readings <- n
		}
	}()
	total := 0
	for n := range readings {
		total += n
	}
	fmt.Println(total)
}
Output
11

The sends deliver 4 and 7. Closing the channel allows the range loop to finish, so the result is 11 regardless of goroutine scheduling.

Try it yourself

What if the producer sends no values and closes the channel?

Check your answer

The range loop finishes immediately and the total is zero.

A Tour of Go

Related tags

  • Go
  • goroutines
  • channels
  • concurrency