concurrent.go:sync.WaitGroupを使用せずにデッドロックを防ぐ方法は?
package main
import (
"fmt"
"sync"
)
// JOBS represents the number of jobs workers do
const JOBS = 2
// WORKERS represents the number of workers
const WORKERS = 5
func work(in <-chan int, out chan<- int, wg *sync.WaitGroup) {
for n := range in {
out <- n * n
}
wg.Done()
}
var wg sync.WaitGroup
func main() {
in := make(chan int, JOBS)
out := make(chan int, JOBS)
for w := 1; w <= WORKERS; w++ {
wg.Add(1)
go work(in, out, &wg)
}
for j := 1; j <= JOBS; j++ {
in <- j
}
close(in)
wg.Wait()
close(out)
for r := range out {
fmt.Println("result:", r)
}
// This is a solution but I want to do it with `range out`
// and also without WaitGroups
// for r := 1; r <= JOBS; r++ {
// fmt.Println("result:", <-out)
// }
}
例goplayにhereです。
あなたは最終的にチャネルを閉じずに範囲を使用することはできません、あなたは待たずにチャンネルを閉じることはできません。あなたは何を達成しようとしていますか? (WaitGroupが存在しない時がありましたが、チャネルから手動でトークンを数えましたが、それはもっとコードでは同じ概念です) – JimB
標準的な方法であるミューテックスや原子カウンターは必要ありませんWaitGroupの前のgoroutinesは、チャネルを通じて返された値をカウントすることでした。 – JimB
これは状況によって異なりますが、コード内にコメントアウトされた例があります。あなたはあなたが派遣した仕事の数に達するまで、結果の数を受け取ります。 – JimB