Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Simple pool of goroutine workers with input/output channels
// Worker pool example with input and output channel and multiple workers
// solves the deadlock caused by the r chanel not read on time, so blocking all
// worker on ri <- v
package main
import (
"fmt"
"time"
"sync"
)
func main () {
c := make(chan int)
r := make(chan int)
var w sync.WaitGroup
for i := 1; i <= 5; i++ {
w.Add(1)
go func(i int, ci <-chan int, ri chan int) {
defer w.Done()
j := 1
for v := range ci {
time.Sleep(time.Millisecond)
j += 1
ri <- v
}
}(i, c, r)
}
// This SOLVES the deadlock, the input channel is
// populated from own goroutine
w.Add(1)
go func(ci <-chan int) {
defer w.Done()
for i := 1; i <= 25; i++ {
c <- i
}
}(c)
for i := 1; i <= 25; i++ {
msg := <-r
fmt.Printf("msg=%d\n", msg)
}
close(c)
w.Wait()
close(r)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment