Go Concurrency Patterns

A Comprehensive Guide

Go concurrency patterns use goroutines and channels to coordinate tasks, as shown by the Fibonacci pipeline example.

Go concurrency patterns rely on goroutines for lightweight threads and channels for safe communication between them. The provided fib.go example demonstrates a pipeline pattern where two fibber goroutines pass *big.Int values through a channel c to compute Fibonacci numbers, while runtime.LockOSThread() ensures they run on dedicated OS threads for testing pthread coordination.

func fibber(c chan *big.Int, out chan string, n int64) {
	runtime.LockOSThread()
	i := big.NewInt(n)
	if n == 0 {
		c <- i
	}
	for {
		j := <-c
		out <- j.String()
		i.Add(i, j)
		c <- i
	}
}

func main() {
	c := make(chan *big.Int)
	out := make(chan string)
	go fibber(c, out, 0)
	go fibber(c, out, 1)
	for i := 0; i < 200; i++ {
		println(<-out)
	}
}