Skip to content

Instantly share code, notes, and snippets.

@nametake
Last active April 5, 2017 05:11
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 nametake/510b34bb8963615e88da847b833c05f7 to your computer and use it in GitHub Desktop.
Save nametake/510b34bb8963615e88da847b833c05f7 to your computer and use it in GitHub Desktop.
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