我正在练习使用通道来实现队列。具体来说,我正在尝试使用通道的大小来限制同时运行的 goroutine 的数量。也就是说,我编写了以下代码:
package main
import "fmt"
import "time"
import "math/rand"
func runTask (t string, ch *chan bool) {
start := time.Now()
fmt.Println("starting task", t)
time.Sleep(time.Millisecond * time.Duration(rand.Int31n(1500))) // fake processing time
fmt.Println("done running task", t, "in", time.Since(start))
<- *ch
}
func main() {
numWorkers := 3
files := []string{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j"}
activeWorkers := make(chan bool, numWorkers)
for _, f := range files {
activeWorkers <- true
fmt.Printf("activeWorkers is %d long.\n", len(activeWorkers))
go runTask(f, &activeWorkers)
}
select{}
}
现在,代码崩溃了:
throw: all goroutines are asleep - deadlock!
我的期望是对 select 的调用将永远阻塞,并让 goroutine 终止而不会出现死锁。
所以我有一个双重问题:为什么不选择永远阻塞,并且在 for 循环之后没有抛出 time.Sleep() 调用,我怎样才能避免死锁?
干杯,
-mtw