DEV Community

Camille
Camille

Posted on

Channel push non blocking in GoLang

By default push operations to golang channel will block once the channel is full and wait that an other go routine will consume a message from the channel.

The following example will block after 3 messages queued in the channel, and since no other go routine is running it will crash with a dead lock error:

package main

import "fmt"

func main() {
    ch := make(chan string, 3)

    for i := 0; i < 10; i++ {
        ch <- "hello"
        fmt.Println("Pushed a message to the channel")
    }
}
Enter fullscreen mode Exit fullscreen mode

To avoid blocking the execution of your application you can handle the case of a full channel by using select:

package main

import "fmt"

func main() {
    ch := make(chan string, 3)

    for i := 0; i < 10; i++ {
        select {
        case ch <- "hello":
            fmt.Println("Pushed a message to the channel")
        default:
            fmt.Println("WARN: The channel is full")
        }
    }
}

Enter fullscreen mode Exit fullscreen mode

This way you can easily decide to ignore the message or handle this problem an other way than blocking the current go routine.

Top comments (0)