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.

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

报告相同问题?

悬赏问题

  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序
  • ¥15 onvif+openssl,vs2022编译openssl64
  • ¥15 iOS 自定义输入法-第三方输入法
  • ¥15 很想要一个很好的答案或提示
  • ¥15 扫描项目中发现AndroidOS.Agent、Android/SmsThief.LI!tr
  • ¥15 怀疑手机被监控,请问怎么解决和防止
  • ¥15 Qt下使用tcp获取数据的详细操作