Go言語でゴルーチンを使う際の
イディオムというか以下のような処理がバッドノウハウかどうかをお聞きします。
go
1 2package main 3 4import ( 5 "fmt" 6 "math/rand" 7 "sync" 8 "time" 9) 10 11var wait *sync.WaitGroup 12var commonBool bool 13 14func main() { 15 wait = &sync.WaitGroup{} 16 // Need to wait 1 delta count. 17 wait.Add(1) 18 go HeavyFunction(wait, &commonBool) 19 wait.Wait() 20 if commonBool == true { 21 fmt.Println("Succeeded completing Goroutine. ") 22 } else { 23 fmt.Println("Failed completing Goroutine. ") 24 } 25} 26 27// Quite function which has heavy process. 28func HeavyFunction(w *sync.WaitGroup, b *bool) { 29 30 // It is a process to wait 5 seconds. 31 time.Sleep(time.Second * 5) 32 fmt.Println("Completed waiting 5 seconds.") 33 34 // Notice completing subroutine to main thread. 35 var r *rand.Rand = rand.New(rand.NewSource(150)) 36 r.Seed(time.Now().Unix()) 37 var i int = r.Intn(9) 38 if (i % 2) == 0 { 39 // Success when getting zero. 40 *b = true 41 w.Done() 42 } else { 43 // Fail when getting not zero. 44 *b = false 45 w.Done() 46 } 47}
HeavyFunction という5秒ほどかかる処理があったとして、
同関数内で、仮に偶数の場合true、奇数の場合falseとします。
その場合、*sync.WaitGroup.Done();でゴルーチンを終了させ、main関数内でゴルーチンの成功あるは失敗を引数に渡したグローバル変数のポインタで判断したのですが、これはプロダクションとして利用してよいのものでしょうか?
また、これをWaitGroupではなくChannelを利用した場合は
go
1// channelを利用した場合 2package main 3 4import ( 5 "fmt" 6 "math/rand" 7 "sync" 8 "time" 9) 10 11var wait *sync.WaitGroup 12var commonBool bool 13 14// チャンネルの場合 15var ch chan int 16var result chan bool 17 18func main() { 19 result = make(chan bool) 20 go HeavyFunctionUsingChannel(result) 21 22 // 23 var res bool 24 res = <-result 25 if res == true { 26 fmt.Println("Succeeded completing Goroutine. ") 27 } else { 28 fmt.Println("Failed completing Goroutine. ") 29 } 30} 31 32 33func HeavyFunctionUsingChannel(result chan bool) { 34 35 // Heavy Process. 36 time.Sleep(time.Second * 5) 37 fmt.Println("Comleted waiting 5 seconds using channel.") 38 39 var r *rand.Rand = rand.New(rand.NewSource(2434)) 40 r.Seed(time.Now().Unix()) 41 if (r.Intn(9) % 2) == 0 { 42 result <- true 43 } else { 44 result <- false 45 } 46} 47
上記のように var result chan bool というchannelで成功あるいは失敗とゴルーチンの終了そのものを兼用しています。
よりよいグッドノウハウがあればご教授をお願いいたします。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2019/04/29 14:34