Skip to content

Instantly share code, notes, and snippets.

@matsu-chara
Last active August 29, 2015 14:06
Show Gist options
  • Save matsu-chara/af153f7272deb3d37bc7 to your computer and use it in GitHub Desktop.
Save matsu-chara/af153f7272deb3d37bc7 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"sync"
)
func work(num int, ch chan int) {
// Do Somthing
ch <- num
}
// Version 1 must know morker num for check
func workWrap(work_num int, ch chan int) {
for i := 0; i < work_num; i++ {
go work(i, ch)
}
}
func checkWork(work_num int, ch chan int) {
for i := 0; i < work_num; i++ {
fmt.Println(<-ch)
}
}
// Version 2 no worker num for check
func workWrap2(work_num int, ch chan int, fin chan int) {
var wg sync.WaitGroup
for i := 0; i < work_num; i++ {
wg.Add(1)
go func(i int) {
work(i, ch)
wg.Done()
}(i)
}
wg.Wait()
fin <- 1
}
func checkWork2(ch chan int, fin chan int) {
for {
select {
case v := <-ch:
fmt.Println(v)
case <-fin:
return
}
}
}
// Version 3 no fin channel for check
func workWrap3(work_num int, ch chan int) {
var wg sync.WaitGroup
for i := 0; i < work_num; i++ {
wg.Add(1)
go func(i int) {
work(i, ch)
wg.Done()
}(i)
}
wg.Wait()
close(ch)
}
func checkWork3(ch chan int) {
for v := range ch {
fmt.Println(v)
}
}
func main() {
ch := make(chan int)
const WorkerNum = 10
// Version 1 must know morker num for check
go workWrap(WorkerNum, ch)
checkWork(WorkerNum, ch)
// Version 2 no worker num for check
fin := make(chan int)
go workWrap2(WorkerNum, ch, fin)
checkWork2(ch, fin)
// Version 3 no fin channel for check
go workWrap3(WorkerNum, ch)
checkWork3(ch)
}
@matsu-chara
Copy link
Author

version3だとcloseで終了してる
同じような書き方だけど記述量が少なくて、finチャンネルも書かなくてすむ

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment