golang频道无法使用或发布

时间:2014-10-14 17:14:32

标签: go channel

在我的下面的代码中,只是整个代码的一部分。我初始化一个频道,频道无法使用或发布。我不知道是什么导致这种情况发生。

//init at the beginning of program
var stopSvr chan bool
stopSvr=make(chan bool)
var stopSvrDone chan bool
stopSvrDone=make(chan bool)

//somewhere use,in a goroutine
select{
    case <-stopSvr:
        stopSvrDone<-true
        fmt.Println("son svr exit")
    default:
        //do its job
}

//somewhere use,in a goroutine
stopSvr <- true //block here
<-stopSvrDone
fmt.Println("svr exit")

//here to do other things,but it's blocked at "stopSvr<-true",
//what condition could make this happen?

结论: 频道的阻止和解锁,我不清楚。 选择{} expr关键字'默认',我不清楚。 这就是我的程序没有运行的原因。

谢谢@jimt,我完成了这个问题。

1 个答案:

答案 0 :(得分:0)

我不确定你想要实现的目标。但是你的示例代码肯定会在select语句中阻塞。

选择的default情况用于在通道上的特定读取或写入不成功时提供回退。这意味着在您的代码中,始终执行默认情况。在选择开始之前,没有任何值写入通道,因此永远不会运行case语句。

default情况下的代码永远不会成功并无限期阻塞,因为通道中没有空间来存储值,其他任何人都没有从其中读取任何其他goroutines。

解决您当前问题的简单方法是:

stopSvr=make(chan bool, 1) // 1 slot buffer to store a value

然而,如果不了解您想要实现的目标,我无法保证这将解决您的所有问题。