DEV Community

Camille
Camille

Posted on

2

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.

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more