How to know a buffered channel is full

后端 未结 4 864
天命终不由人
天命终不由人 2021-01-30 02:07

How to know a buffered channel is full? I don\'t know to be blocked when the buffered channel is full, instead I choose to drop the item sent to the buffered channel.

4条回答
  •  爱一瞬间的悲伤
    2021-01-30 02:47

    instead I choose to drop the item sent to the buffered channel.

    That is called "overflowing channel", and you find ANisus's answer implemented in eapache/channels/overflowing_channel.go:

    for elem := range ch.input {
        // if we can't write it immediately, drop it and move on
        select {
        case ch.output <- elem:
        default:
        }
    }
    close(ch.output)
    

    But that project eapache/channels implements other strategies as well:

    • OverflowingChannel implements the Channel interface in a way that never blocks the writer.
      Specifically, if a value is written to an OverflowingChannel when its buffer is full
      (or, in an unbuffered case, when the recipient is not ready) then that value is simply discarded.

    For the opposite behaviour (discarding the oldest element, not the newest) see RingChannel.

提交回复
热议问题