๐ŸŽ“ A1Learner
๐Ÿ”

Go Goroutines

A goroutine is a function that runs at the same time as other functions. Goroutines pass values to each other through channels.

Wait for a Goroutine

Main starts the worker and then waits on the WaitGroup. The worker line prints before the main line.

package main

import (
	"fmt"
	"sync"
)

func worker(wg *sync.WaitGroup) {
	defer wg.Done()
	fmt.Println("Worker finished.")
}

func main() {
	var wg sync.WaitGroup
	wg.Add(1)
	go worker(&wg)
	wg.Wait()
	fmt.Println("Main finished.")
}

Receive From a Channel

The send blocks until main receives the value. The hand-off fixes the order of the print.

package main

import "fmt"

func send(ch chan string) {
	ch <- "ping"
}

func main() {
	ch := make(chan string)
	go send(ch)
	message := <-ch
	fmt.Println("Received:", message)
}

A Buffered Channel

This channel holds two values before it blocks. The values come back in send order.

package main

import "fmt"

func main() {
	ch := make(chan int, 2)
	ch <- 1
	ch <- 2
	fmt.Println(<-ch)
	fmt.Println(<-ch)
}

Example

package main

import "fmt"

func doubleAll(numbers []int, ch chan int) {
	for _, number := range numbers {
		ch <- number * 2
	}
}

func main() {
	ch := make(chan int)
	go doubleAll([]int{1, 2, 3}, ch)
	first := <-ch
	second := <-ch
	third := <-ch
	fmt.Println(first, second, third)
}

Key points

  • Goroutine: a function that runs at the same time as other functions.
  • Use the go keyword before a call to start a goroutine.
  • Channel: a typed path that passes values between goroutines.
  • Make a channel with make and the chan keyword.
  • A WaitGroup counts running goroutines, and Wait blocks until the count reaches zero.
  • The waits in these examples are what fix the print order.
  • Later courses cover select, mutexes, and fan-out patterns.

In this example, the goroutine doubles each number and sends the result into the channel. Each send blocks until main receives the value. Main receives the three values in send order. The doubled numbers 2, 4, and 6 print on one line.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Go Playground

Exercise

Why does the worker line print before the main line in the WaitGroup example?