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:
go f()doesn't wait forfto finish. The next line runs right away.- When
mainreturns, 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".
- Complete
jumlahkan(bagian []int, hasil chan int)so it adds up every number inbagianand then sends the total tohasil. - Complete
totalParalel(transaksi []int) int:- split
transaksiinto two parts,transaksi[:tengah]andtransaksi[tengah:], withtengah := len(transaksi) / 2, - run
jumlahkanon each part as a goroutine, using one shared unbuffered channel, - receive the two results from the channel and return their sum.
- split