Go   发布时间:2022-04-09  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了为什么我用这个Golang代码遇到死锁?大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我对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)
}

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

result =  <-in && result,

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

非常感谢你提前.

解决方法

你可以看到 here,&&的正确操作数.有条件地评估.

这意味着结果=结果&& < -in只会在结果为真时评估< -in.因此,coodrinator只从该频道中读取一个错误,并跳过从其他工作者那里读取消息.如果你切换&&的操作数在那里,然后< -in将每次评估并且死锁消失.

大佬总结

以上是大佬教程为你收集整理的为什么我用这个Golang代码遇到死锁?全部内容,希望文章能够帮你解决为什么我用这个Golang代码遇到死锁?所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: