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.

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs