Created
October 10, 2018 15:10
-
-
Save vyskocilm/d0c1a2f57a9b0821c00f31190c167781 to your computer and use it in GitHub Desktop.
Simple pool of goroutine workers with input/output channels
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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