【发布时间】:2018-03-29 23:27:15
【问题描述】:
附加的要点是一个在生产者/多消费者模型中使用通道的简单程序。不知为何,
go run channels.go 打印所有结果但不返回(并且不会死锁,或者至少 go 不会让我担心发生死锁。)
type walkietalkie struct {
in chan int
out chan int
quit chan bool
}
var items []int = []int{
0, 1, 2, 3, 4, 5,
}
func work1(q walkietalkie) {
for {
select {
case a, more := <- q.in:
if more {
q.out <- a * 2
}
default:
break
}
}
}
func work2(q walkietalkie) {
for {
select {
case a, more := <- q.in:
if more {
q.out <- a * -1
}
default:
break
}
}
}
func work3(q walkietalkie) {
for {
select {
case a, more := <- q.in:
if more {
q.out <- a * 7
}
default:
break
}
}
}
func main() {
results := make(chan int, 18)
defer close(results)
w := []walkietalkie{
walkietalkie{ in: make(chan int, 6), out: results, quit: make(chan bool, 1) },
walkietalkie{ in: make(chan int, 6), out: results, quit: make(chan bool, 1) },
walkietalkie{ in: make(chan int, 6), out: results, quit: make(chan bool, 1) },
}
go work1(w[0])
go work2(w[1])
go work3(w[2])
// Iterate over work items
l := len(items)
for i, e := range items {
// Send the work item to each worker
for _, f := range w {
f.in <- e // send the work item
if i == l - 1 { // This is the last input, close the channel
close(f.in)
}
}
}
// Read all the results from the workers
for {
select {
case r, more := <-results:
if more {
fmt.Println(r)
} else {
continue
}
default:
break
}
}
}
【问题讨论】:
-
在这里发布代码。接收到所有值后,main 函数在一个紧密的循环中旋转。
-
select 语句没有意义。看来您正在寻找for/range loops。
-
main一直运行到results关闭,但results直到main返回才关闭。因此main中的最后一个for循环将永远运行。而且即使正确关闭,default: break也只会从select中跳出,而不是在for之外,所以它仍然会永远运行。