Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
package main
import (
"fmt"
"sync"
"time"
)
func main() {
d := &dispatcher{
in: make(chan int),
out: make(chan int),
}
d.run(3)
d.run(2)
go func() {
for i := range d.output() {
fmt.Println(i)
}
}()
go func() {
for i := 0; i < 30; i++ {
d.input() <- i
}
d.stop()
}()
d.wait()
}
type dispatcher struct {
wg sync.WaitGroup
in chan int
out chan int
}
func (d *dispatcher) work() {
d.wg.Add(1)
defer d.wg.Done()
for i := range d.in {
// ここにロジックを書く(ここでは100倍するだけ)
time.Sleep(time.Second)
d.out <- i * 100
}
}
func (d *dispatcher) input() chan<- int {
return d.in
}
func (d *dispatcher) output() <-chan int {
return d.out
}
func (d *dispatcher) run(n int) {
for i := 0; i < n; i++ {
go d.work()
}
}
func (d *dispatcher) stop() {
close(d.in)
}
func (d *dispatcher) wait() {
d.wg.Wait()
close(d.out)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment