Channel push non blocking in GoLang
Camille
Posted on November 11, 2020
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")
}
}
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")
}
}
}
This way you can easily decide to ignore the message or handle this problem an other way than blocking the current go routine.
💖 💪 🙅 🚩
Camille
Posted on November 11, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.