Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you make Golang drop packets on writes rather than block?

Tags:

go

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

like image 795
Nicomoto Avatar asked Oct 02 '13 21:10

Nicomoto


1 Answers

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
        }
    }
}
like image 75
creack Avatar answered Oct 14 '22 22:10

creack