In this article, we will see how to use timeouts with channels in golang.

What are channels in golang?

Channels are a powerful tool for communicating between goroutines. However, in some scenarios we may need to set a timeout for a channel operation to avoid blocking indefinitely.

By using the timeouts, we can prevent the program from blocking indefinitely.

To use timeouts with channels in Golang, we can use the “select” statement, which allows us to wait for multiple channel operations to complete simultaneously.

package main

import (
    "fmt"
    "time"
)

func main() {
    c := make(chan int)

    // Sending data to the channel after a delay
    go func() {
        time.Sleep(2 * time.Second)
        c <- 42
    }()

    // Waiting for data from the channel with a timeout
    select {
    case i := <-c:
        fmt.Println("Received data from channel:", i)
    case <-time.After(1 * time.Second):
        fmt.Println("Timed out waiting for data")
    }
}

In the above example, we first create a channel named “c” and then we used a goroutine to send data to the channel after the delay of 2 seconds. Finally, we use the “select” statement to wait for data from the channel with a timeout of 1 second.

Following is the output that we got after running the above code

Timed out waiting for data

Categorized in:

Tagged in: