Go course

ChannelsGoroutines and Channels

Go

Display

Theme

Channels · Test exercise

Goroutines and Channels

Goroutine

A goroutine is a function that runs concurrently with the rest of your code. To start one, just put the go keyword in front of a function call:

func seduh(menu string) {
	fmt.Println("menyeduh", menu)
}

func main() {
	go seduh("latte")    // berjalan di goroutine baru
	go seduh("espresso") // goroutine lain
	fmt.Println("kasir melayani pelanggan berikutnya")
}

Goroutines are very lightweight: a Go program can run thousands, even millions, of them. There are two important things to keep in mind, though:

  1. go f() doesn't wait for f to finish. The next line runs right away.
  2. When main returns, the program stops, including every goroutine that hasn't finished yet. The program above will most likely print only the cashier line (kasir melayani pelanggan berikutnya, "the cashier serves the next customer").

We need a way to wait for goroutines and get their results back. That's where channels come in.

Channel

A channel is a typed "pipe" for sending values between goroutines.

ch := make(chan int) // channel untuk nilai int

ch <- 42    // KIRIM 42 ke channel
v := <-ch   // TERIMA nilai dari channel

A channel created with make(chan T) is unbuffered: a send waits (blocks) until another goroutine receives, and a receive waits until someone sends. Both sides "meet" at that point, so the channel doubles as a synchronization tool.

func hitungKalori(menu []int, hasil chan int) {
	total := 0
	for _, k := range menu {
		total += k
	}
	hasil <- total // kirim hasil
}

func main() {
	hasil := make(chan int)
	go hitungKalori([]int{120, 300}, hasil)
	go hitungKalori([]int{80, 90, 150}, hasil)

	a := <-hasil // menunggu salah satu goroutine selesai
	b := <-hasil // menunggu goroutine yang lain
	fmt.Println(a + b) // 740
}

The order of a and b can change from run to run (it depends on which goroutine finishes first), but their sum is always the same. When you write concurrent programs, design them so the final result doesn't depend on scheduling order.

Task

A point-of-sale system wants to add up the day's transactions using two parallel "workers".

  1. Complete jumlahkan(bagian []int, hasil chan int) so it adds up every number in bagian and then sends the total to hasil.
  2. Complete totalParalel(transaksi []int) int:
    • split transaksi into two parts, transaksi[:tengah] and transaksi[tengah:], with tengah := len(transaksi) / 2,
    • run jumlahkan on each part as a goroutine, using one shared unbuffered channel,
    • receive the two results from the channel and return their sum.
main.go
package main

import "fmt"

func jumlahkan(bagian []int, hasil chan int) {
	// TODO: jumlahkan isi bagian lalu kirim totalnya ke channel hasil
	hasil <- 0
}

func totalParalel(transaksi []int) int {
	// TODO: bagi dua, jalankan dua goroutine jumlahkan, terima 2 hasil
	return 0
}

func main() {
	transaksi := []int{25000, 18000, 42000, 7000, 31000}
	fmt.Println("Total:", totalParalel(transaksi))
}

Output

Go runtime not loaded yet

Press Run to see the output, or Submit to check your code.

Ctrl/Cmd + Enter: Run · Ctrl/Cmd + Shift + Enter: Submit · Ctrl/Cmd + S: tidy the code (gofmt)