Skip to content

Instantly share code, notes, and snippets.

@vyskocilm
Created October 10, 2018 15:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vyskocilm/d0c1a2f57a9b0821c00f31190c167781 to your computer and use it in GitHub Desktop.
Save vyskocilm/d0c1a2f57a9b0821c00f31190c167781 to your computer and use it in GitHub Desktop.
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