为什么我用这个Golang代码遇到死锁?

Lon*_*ham 4 deadlock go

我对Golang很新.我为练习编写了以下代码,并遇到了死锁的运行时错误消息:

package main

import (
    "fmt"
)

func system(WORKERS int) {
    fromW := make(chan bool)
    toW := make(chan bool)
    for i := 0; i != WORKERS; i++ {
        go worker(toW, fromW)
    }
    coordinator(WORKERS, fromW, toW)
}

func coordinator(WORKERS int, in, out chan bool) {
    result := true
    for i := 0; i != WORKERS; i++ {
        result =  result && <-in
    }
    for i := 0; i != WORKERS; i++ {
        out <- result
    }
    fmt.Println("%t", result)
}

func worker(in, out chan bool) {
    out <- false
    <-in
}

func main() {
    system(2)
}
Run Code Online (Sandbox Code Playgroud)

但是,如果我在第19行交换&&的操作数

result =  <-in && result,
Run Code Online (Sandbox Code Playgroud)

代码正常工作,不返回任何错误消息.我该如何解释这种行为?我在这里错过了什么吗?我使用的操作系统是Windows 10,Golang版本是1.8.3.

非常感谢你提前.

小智 6

正如您在此处所见,正确&&评估了右操作数.

这意味着result = result && <-in只评估<-inif是否result为真.因此,coodrinator只读取false该频道中的一个,并跳过阅读其他工作人员的消息.如果你切换&&场所的操作数,那么<-in每次都会评估并且死锁消失.