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)
// }
}
實施例是here上goplay。
不能使用範圍,而最終關閉通道,你可以不等待關閉通道。你試圖完成什麼? (順便說一句,WaitGroup不存在的時候,我們只是手動計算來自通道的令牌,但在更多代碼中它仍然是相同的概念) – JimB
您不需要互斥或原子計數器,這是等待的標準方式WaitGroup之前的goroutines計算通過通道返回的值。 – JimB
這取決於具體情況,但您在自己的代碼中有一個註釋示例。直到達到您分派的JOBS數量爲止,您會收到結果數量。 – JimB