Sobes.tech
Senior

What concurrency patterns do you know in Go?

sobes.tech AI

Answer from AI

In Go, there are several common concurrency patterns that help efficiently work with goroutines and channels:

  • Worker Pool — a pool of workers that receive tasks from a channel and process them in parallel. It allows limiting the number of goroutines working simultaneously.

  • Fan-out, Fan-in — a pattern where multiple goroutines (fan-out) process data in parallel, and results are collected into a single channel (fan-in).

  • Pipeline — a sequence of data processing stages, each implemented in a separate goroutine connected by channels.

  • Select for multiplexing — allows a goroutine to wait on multiple channels and react to the first one that becomes available.

  • Mutex and RWMutex — for protecting shared resources during concurrent access.

  • Context — for managing the lifetime of goroutines and canceling operations.

Example of Worker Pool:

func worker(id int, jobs <-chan int, results chan<- int) {
    for j := range jobs {
        fmt.Printf("worker %d processing job %d\n", id, j)
        results <- j * 2
    }
}

func main() {
    jobs := make(chan int, 5)
    results := make(chan int, 5)

    for w := 1; w <= 3; w++ {
        go worker(w, jobs, results)
    }

    for j := 1; j <= 5; j++ {
        jobs <- j
    }
    close(jobs)

    for a := 1; a <= 5; a++ {
        fmt.Println(<-results)
    }
}