在尝试发送之前,进行非阻塞通道发送,测试是否失败?

huangapple go评论85阅读模式
英文:

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 := &quot;hi&quot;
select {
    case messages &lt;- msg:
        fmt.Println(&quot;sent message&quot;, msg)
    default:
        fmt.Println(&quot;no message sent&quot;)
    }

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 &lt;-ready:
        msg := generateMsg()
        messages &lt;- msg
        fmt.Println(&quot;sent message&quot;, msg)
    default:
        fmt.Println(&quot;no message sent&quot;)
}

or you can use a sync.Cond

huangapple
  • 本文由 发表于 2015年3月13日 01:12:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/29016118.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定