golang:select语句中的通道有时只接收(???)

时间:2015-01-17 13:12:18

标签: select go channel

我在一个go例程中有一个select语句,它从两个通道接收。

for {
    fmt.Printf("Waiting for select statement ...\n")
    select {
    case req := <-requestChan:
        fmt.Printf("I got a request: %v\n", req)
    case <-doneChan:
        fmt.Printf("serveDatabase: Got closing signal. Stop serving.\n")
        return
    }
}

如果调用函数发送到第一个通道两次然后发送到第二个通道,一切正常:

requestChan <- Db_request{ request: "Login", beehive: "yaylaswiese" }
requestChan <- Db_request{ request: "Signup", beehive: "aziz nezir" }

fmt.Printf("Sending true to the doneChannel\n")
doneChan <- true

控制台输出(正确)是:

>     Waiting for select statement ...
>     I got a request: {Login yaylaswiese}
>     Waiting for select statement ...
>     Sending true to the doneChannel
>     I got a request: {Signup aziz nezir}
>     Waiting for select statement ...
>     serveDatabase: Got closing signal. Stop serving.

但是,如果我评论第二个请求,如

requestChan <- Db_request{ request: "Login", beehive: "yaylaswiese" }
// requestChan <- Db_request{ request: "Signup", beehive: "aziz nezir" }

fmt.Printf("Sending true to the doneChannel\n")
doneChan <- true

然后输出

>     Waiting for select statement ...
>     I got a request: {Login yaylaswiese}
>     Waiting for select statement ...
>     Sending true to the doneChannel

所以从未收到过doneChan。在发送doneChan之后我也尝试进入无限循环,但结果相同。

那可能是什么?

1 个答案:

答案 0 :(得分:2)

最有可能的是,您的main在其他goroutine最终确定之前就已退出。请注意,它们是并发的,一旦main完成,所有其他goroutine都会被杀死。

您需要明确地将goroutines的结尾与main同步。 You can use sync.WaitGroup for that或其他渠道。