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