In my code below,just part of the whole code.I init a channel, the channel can't consume or publish.I don't konw what make this happen.
//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?
conclusion: channel's block and unblock,I didn't know clearly. select{} expr keyword 'default',I didn't know clearly. that's why my program didn't run.
thanks @jimt ,I finish the problem.
I am unsure what you are trying to achieve. But your example code is guaranteed to block on the select statement.
The default
case for a select is used to provide a fallback when either a specific read or write on a channel does not succeed. This means that in your code, the default case is always executed. No value is ever written into the channel before the select begins, thus the case
statement is never run.
The code in the default
case will never succeed and block indefinitely, because there is no space in the channel to store the value and nobody else is reading from it in any other goroutines.
A simple solution to your immediate problem would be:
stopSvr=make(chan bool, 1) // 1 slot buffer to store a value
However, without understanding what you want to achieve, I can't guarantee that this will solve all your problems.