Set your Publisher ID in src/config/ads.ts to display live ads.
Concurrency: Goroutines, Channels & Select
Lightweight green threads, channel communication, and the select statement
Go is famous for its Communicating Sequential Processes (CSP) concurrency model: "Do not communicate by sharing memory; instead, share memory by communicating."
Goroutines vs OS Threads
Goroutine: A lightweight thread managed by the Go runtime, starting at just ~2KB of stack memory (compared to ~1MB for OS threads). You can spawn 1,000,000 goroutines concurrently!
Channels (ch := make(chan int)): Typed conduits through which goroutines synchronize and exchange data without race conditions.
select: Multiplexes communication over multiple channels, waiting until one is ready to send or receive.
package main
import "fmt"
func fetchMetric(id int, ch chan<- string) {
// Heavy work simulation...
ch <- fmt.Sprintf("Metric from worker #%d", id)
}
func main() {
ch := make(chan string, 3) // Buffered channel
// Spawn 3 concurrent goroutines with 'go' keyword
for i := 1; i <= 3; i++ {
go fetchMetric(i, ch)
}
// Collect responses from channel
for i := 1; i <= 3; i++ {
msg := <-ch
fmt.Println("Received:", msg)
}
}Set your Publisher ID in src/config/ads.ts to display live ads.
Test Yourself With Exercise
Which keyword in Go spawns a function as a lightweight concurrent goroutine?