加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

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

发布时间:2020-12-16 09:25:33 所属栏目:大数据 来源:网络整理
导读:我对Golang很新.我为练习编写了以下代码,并遇到了死锁的运行时错误消息: package mainimport ( "fmt")func system(WORKERS int) { fromW := make(chan bool) toW := make(chan bool) for i := 0; i != WORKERS; i++ { go worker(toW,fromW) } coordinator(W
我对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将每次评估并且死锁消失.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读