ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)

Set your Publisher ID in src/config/ads.ts to display live ads.

Go (Golang) Tutorial• 8 min read

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.

Producer-Consumer with Channels and Goroutines
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)
    }
}
ADVERTISEMENT
Google AdSense Slot (inContentBanner)

Set your Publisher ID in src/config/ads.ts to display live ads.

Test Yourself With Exercise

+15 XP

Which keyword in Go spawns a function as a lightweight concurrent goroutine?