AdvancedLesson 12 of 15
Goroutines & Channels – Go
Concurrency that feels like normal code.
A goroutine is an extremely lightweight thread of execution managed by the Go runtime. go f() starts f concurrently – thousands of goroutines are no problem. Without synchronization, however, main ends before they finish; sync.WaitGroup waits for them.
package main
import (
"fmt"
"sync"
)
func main() {
var wg sync.WaitGroup
for i := 1; i <= 3; i++ {
wg.Add(1)
go func() {
defer wg.Done()
fmt.Println("Worker", i) // order is unpredictable
}()
}
wg.Wait()
}Goroutines communicate through channels: typed conduits through which values flow. "Share memory by communicating – not the other way around." Sending on an unbuffered channel blocks until someone receives. With close the sender announces: "Nothing more is coming."
package main
import "fmt"
func main() {
ch := make(chan int)
go func() {
for i := 1; i <= 3; i++ {
ch <- i * i
}
close(ch)
}()
for v := range ch { // runs until the channel is closed
fmt.Println(v) // 1 4 9
}
puffer := make(chan string, 2) // buffered: 2 values without a receiver
puffer <- "a"
puffer <- "b"
fmt.Println(<-puffer, <-puffer) // a b
}select waits on several channel operations at once – ideal for timeouts. A default case makes the operation non-blocking.
package main
import (
"fmt"
"time"
)
func main() {
ergebnis := make(chan string)
go func() {
time.Sleep(50 * time.Millisecond)
ergebnis <- "done"
}()
select {
case r := <-ergebnis:
fmt.Println(r) // done
case <-time.After(time.Second):
fmt.Println("Timeout")
}
leer := make(chan int)
select {
case v := <-leer:
fmt.Println(v)
default:
fmt.Println("nothing here") // nothing here
}
}WarningA program in which all goroutines are waiting for something that never comes ends with
fatal error: all goroutines are asleep - deadlock!. Only the sender closes a channel; sending on a closed channel causes a panic. Since Go 1.25 there is also wg.Go(func() { ... }) as a shorthand for Add + go + Done.TipCheck concurrent code with
go run -race . or go test -race ./... – the race detector finds accesses by several goroutines to the same data without synchronization.