How to know a buffered channel is full

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

    You can use the select statement with a default. In case it is not possible to do any of the cases, like sending to a full channel, the statement will do the default:

    package main
    
    import "fmt"
    
    func main() {
        ch := make(chan int, 1)
    
        // Fill it up
        ch <- 1
    
        select {
        case ch <- 2: // Put 2 in the channel unless it is full
        default:
            fmt.Println("Channel full. Discarding value")
        }
    }
    

    Output:

    Channel full. Discarding value

    Playground: http://play.golang.org/p/1QOLbj2Kz2

    Check without sending

    It is also possible to check the number of elements queued in a channel by using len(ch), as stated in the Go specifications. This in combination with cap allows us to check if a channel is full without sending any data.

    if len(ch) == cap(ch) {
        // Channel was full, but might not be by now
    } else {
        // Channel wasn't full, but might be by now
    }
    

    Note that the result of the comparison may be invalid by the time you enter the if block

提交回复
热议问题