How to know a buffered channel is full

后端 未结 4 857
天命终不由人
天命终不由人 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:53

    I use this code to remove one item if the channel was full. For channels with only one sending go routine it's enough to ensure that sending to ch will work afterwards.

    // Remove one item from chan if full
    if len(ch) == cap(ch) {
        // Channel was full, but might not be by now
        select {
        case _ := <-ch:
        // Discard one item
        default:
            // Maybe it was empty already
        }
    }
    
    // Now we can send to channel
    

提交回复
热议问题