我在从两个通道接收的 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 回答
慕无忌1623718
TA贡献1744条经验 获得超4个赞
最有可能的main
是,您在另一个 goroutine 完成之前就退出了。请注意,它们是并发的,一旦main
完成,所有其他 goroutine 都会被杀死。
您需要显式地将 goroutine 的结尾与main
. 您可以使用 sync.WaitGroup或其他频道。
- 1 回答
- 0 关注
- 189 浏览
添加回答
举报
0/150
提交
取消