Home > Backend Development > Golang > Why Doesn't My Golang Timeout Case Trigger When Using Channels?

Why Doesn't My Golang Timeout Case Trigger When Using Channels?

Patricia Arquette
Release: 2024-12-18 11:38:15
Original
818 people have browsed it

Why Doesn't My Golang Timeout Case Trigger When Using Channels?

Timeout Case Not Triggered in Golang with Channels

In the provided code, a timeout case is implemented using a select statement and a time.After() call. However, the timeout case is not getting executed.

Explanation

The reason for this is that the time.After() function creates a new channel each time it is called. When the select statement receives a value from the c1 channel (in the first for loop), the existing time.After() channel is discarded. Thus, the timeout case never has an opportunity to receive a value.

Solution

To resolve this issue, create the time.After() channel only once, outside of the for loop. This ensures that the same channel is used for the timeout case throughout the execution.

Here's the modified code:

func main() {
    c1 := make(chan int, 1)

    go func() {
        for {
            time.Sleep(1500 * time.Millisecond)
            c1 <- 10
        }
    }()

    timeout := time.After(2000 * time.Millisecond)
    for {
        select {
        case i := <-c1:
            fmt.Println(i)
        case <-timeout:
            fmt.Println("TIMEOUT")
        }
    }

    fmt.Scanln()
}
Copy after login

With this modification, the timeout case will be executed successfully after 2 seconds, as long as no value is received from the c1 channel within that time frame.

The above is the detailed content of Why Doesn't My Golang Timeout Case Trigger When Using Channels?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template