dongyuan9149
dongyuan9149
2013-10-02 21:32
浏览 41
已采纳

您能否在写入而不是阻止时使Golang丢弃数据包?

Given a channel of length N, I want to write to it only if it is not full. Else I will drop this packet and process the next one.

Is this possible in GOlang

图片转代码服务由CSDN问答提供 功能建议

给定一个长度为N的通道,我只想在它不满的情况下才写它。 否则,我将丢弃此数据包并处理下一个数据包。

在GOlang中是否可能

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • doudian6229
    doudian6229 2013-10-02 21:51
    已采纳

    You can use select. Example:

    package main
    
    func main() {
    
        ch := make(chan int, 2)
    
        for i := 0; i < 10; i++ {
            select {
            case ch <- i:
                // process this packet
                println(i)
            default:
                println("full")
                // skip the packet and continue
            }
        }
    }
    
    点赞 评论
  • drpp5680
    drpp5680 2014-03-02 04:01

    A bit after the fact I know, but this is exactly what is implemented by the OverflowingChannel type in the helper package I wrote. It effectively uses the select trick above.

    点赞 评论

相关推荐