我正在使用通道实现队列的练习中。具体来说,我正在尝试使用通道的大小来限制并行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在没有死锁的情况下终止。
所以我有两个问题:为什么选择不会永远阻塞,并且没有在time.Sleep()中抛出,在for循环之后调用,如何避免死锁?
牧羊人nacy
相关分类