Home > Backend Development > Golang > Why Doesn't My Go Goroutine Timeout Channel Ever Trigger?

Why Doesn't My Go Goroutine Timeout Channel Ever Trigger?

Linda Hamilton
Release: 2024-12-11 07:10:10
Original
223 people have browsed it

Why Doesn't My Go Goroutine Timeout Channel Ever Trigger?

Goroutine Timeout Channel Never Invoked

When using goroutines and channels in Go, it's essential to understand how timeouts work. In this code snippet, the goal is to print "TIMEOUT" after 2 seconds if no value is received on the channel c1. However, the timeout case is never executed.

Explanation:

The issue lies in the way the timeout channel is created inside the select loop. Each time a value is received from c1, a new timeout channel is created using time.After(...). This effectively cancels the previous timeout and starts a new one. As long as c1 continues to receive values, the timeout channel is constantly reset and never reaches its 2-second expiration.

Solution:

To ensure the timeout is triggered as intended, move the creation of the timeout channel outside the select loop. By creating it only once, the channel remains active until its expiration is reached, regardless of values received from c1.

Modified Code:

func main() {
    c1 := make(chan int, 1)
    timeout := time.After(2000 * time.Millisecond)

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

    for {
        select {
        case i := <-c1:
            fmt.Println(i)
        case <-timeout:
            fmt.Println("TIMEOUT")
        }
    }

    fmt.Scanln()
}
Copy after login

Output:

10
10
10
...
TIMEOUT
Copy after login

Now, after 2 seconds of inactivity on c1, "TIMEOUT" is correctly printed.

The above is the detailed content of Why Doesn't My Go Goroutine Timeout Channel Ever Trigger?. 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