GO Go

Go: Goroutines & Channels

What you will learn

Go's lightweight threads (goroutines) and how channels let them communicate safely.

Goroutines — concurrent execution

A goroutine is a function that runs concurrently with other functions. Start one with the go keyword:

func say(msg string) {
    fmt.Println(msg)
}

go say("hello")  // runs in a new goroutine
say("world")     // runs on the main goroutine

Goroutines are lightweight (a few KB of stack, not a full OS thread). You can start thousands without significant overhead. They multiplex onto OS threads automatically.

Channels — communicate between goroutines

Channels are typed conduits for sending/receiving values:

ch := make(chan string)  // create a channel of strings

// Send in a goroutine
go func() {
    ch <- "done!"        // send into channel
}()

msg := <-ch               // receive from channel (blocks until ready)
fmt.Println(msg)          // done!

Channel direction: ch <- value sends. <-ch receives. Both block by default — sending blocks until someone receives, and vice versa.

Buffered channels

ch := make(chan int, 3)   // buffer of 3
ch <- 1                   // doesn't block (room in buffer)
ch <- 2
ch <- 3
// ch <- 4                // would block — buffer full

Select — multiple channels

select {
case msg1 := <-ch1:
    fmt.Println("from ch1:", msg1)
case msg2 := <-ch2:
    fmt.Println("from ch2:", msg2)
case <-time.After(1 * time.Second):
    fmt.Println("timeout")
}

Quick check below!