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