Go Concurrency

Back to Languages/go

Basic info in README. Sourced from this cool Visualization of Go Concurrency.

Goroutine blocking

Fan-in Design Pattern

Fan-in is a function reading from multiple inputs and multiplexing all into a single channel

Here, producers run concurrently while the reader, also concurrent, waits to recieve using a range loop.

package main

import (
    "fmt"
    "time"
)

func producer(ch chan int, d time.Duration) {
    var i int
    for {
        ch <- i
        i++
        time.Sleep(d)
    }
}

func reader(out chan int) {
    for x := range out {
        fmt.Println(x)
    }
}

func main() {
    ch := make(chan int)
    out := make(chan int)
    go producer(ch, 100*time.Millisecond)
    go producer(ch, 250*time.Millisecond)
    go reader(out)
    for i := range ch { // multiplexing the integers being sent to `ch` channel, sending them to reader
        out <- i
    }
}

visualization of code

Workers (fan-out design pattern)

Opposite of fan-in, multiple goroutines read from a single channel, distributing work between CPU cores. The following is an animation of 36 workers, where GOMAXPROCS=4 (effectively only 4 goroutines in parallel):
36 go workers

Servers design pattern

Similar to fan-out, goroutines are spawned for short period of time to complete a task.