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

golang: channel in select statement is only receiving sometimes (???)

我在从两个通道接收的 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 后进入无限循环,但结果相同。

那会是什么?

很可能,您的 main 在另一个 goroutine 完成之前退出。请注意,它们是并发的,一旦 main 完成,所有其他 goroutines 都会被杀死。

您需要将 goroutine 的结尾与 main 显式同步。 You can use sync.WaitGroup for that,或其他频道。