dongshixingga7900 2017-08-22 07:54
浏览 34
已采纳

为什么我在使用此Golang代码时陷入僵局?

I am quite new to Golang. I wrote the following code for practice and ran into a run-time error message of a deadlock:

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)
}

However, if I swap the operands of && in line 19 to have

result =  <-in && result,

the code works properly without returning any error messages. How can I explain this behaviour? Am I missing anything here? The OS I use is Windows 10, and the Golang version is 1.8.3.

Thank you very much in advance.

  • 写回答

1条回答 默认 最新

  • douganbi7686 2017-08-22 08:11
    关注

    As you can see here, the right operand of && is evaluated conditionally.

    This means that result = result && <-in will only evaluate <-in if result is true. So, the coodrinator reads only one false from that channel, and skips reading messages from the other workers. If you switch the operands of && places, then the <-in will evaluate every time and the deadlock goes away.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?