英文:
Go non-blocking channel send, test-for-failure before attempting to send?
问题
有没有一种方法可以在不实际尝试发送的情况下测试 Go 通道发送的失败?标准的非阻塞发送代码如下:
msg := "hi"
select {
case messages <- msg:
fmt.Println("sent message", msg)
default:
fmt.Println("no message sent")
}
问题是,为了测试通道,我需要准备好要发送的 "msg"。
我想测试发送是否会失败,而不需要准备好要发送的 "msg"。
英文:
Is there a way to test for failure of a go channel send without actually attempting the send? The standard non-blocking send is like so:
msg := "hi"
select {
case messages <- msg:
fmt.Println("sent message", msg)
default:
fmt.Println("no message sent")
}
The problem is that I need to have "msg" ready to send in order to test the channel.
I would like to test to see if a send will fail in a way that does not require having "msg" ready for sending.
答案1
得分: 7
在一般情况下,这样做没有好处,因为这样会导致竞争条件。在生成消息后,通道可能不再准备好发送。
如果你需要这种模式,你可以使用第二个用于信号传递的通道:
select {
case <-ready:
msg := generateMsg()
messages <- msg
fmt.Println("sent message", msg)
default:
fmt.Println("no message sent")
}
或者你可以使用 sync.Cond
。
英文:
That would do no good in the general case, since you then have a race. After generating msg the channel may no longer be ready to send.
If you need this pattern, you either need a second channel for signaling,
select {
case <-ready:
msg := generateMsg()
messages <- msg
fmt.Println("sent message", msg)
default:
fmt.Println("no message sent")
}
or you can use a sync.Cond
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论