Go non-blocking channel send, test-for-failure before attempting to send?

这一生的挚爱 提交于 2019-12-11 07:13:28

问题


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:


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



来源:https://stackoverflow.com/questions/29016118/go-non-blocking-channel-send-test-for-failure-before-attempting-to-send

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!