Home > Backend Development > Golang > How Can I Properly Stop a Goroutine's Execution After a Timeout in Go?

How Can I Properly Stop a Goroutine's Execution After a Timeout in Go?

Mary-Kate Olsen
Release: 2024-12-11 21:30:12
Original
1117 people have browsed it

How Can I Properly Stop a Goroutine's Execution After a Timeout in Go?

Stopping Goroutine Execution with Timeouts in Go

When attempting to terminate goroutine execution upon a timeout, it may appear ineffective. This is because Go's concurrency model operates on the principle of fork-join, where initiating a goroutine (fork) doesn't provide immediate control over its execution. Control is only regained at synchronization points, such as channel communication.

In the given example:

go func() {
    time.Sleep(10 * time.Second)
    fmt.Println("test")
    fmt.Println("test1")
    ch <- Response{data: "data", status: true}
}()
Copy after login

The goroutine continues execution despite the timeout set in:

case <-time.After(50 * time.Millisecond):
    return "Timed out", false
Copy after login

This is because the timeout pertains to the receiver (reader) of the channel, not the sender. As the channel is buffered, the sender can continue executing without interruption.

To achieve the desired behavior, synchronization techniques must be employed. For instance, the channel could be closed upon timeout to prevent further communication:

select {
case <-ch:
    fmt.Println("Read from ch")
    res := <-ch
    return res.data, res.status
case <-time.After(50 * time.Millisecond):
    close(ch)
    return "Timed out", false
}
Copy after login

The above is the detailed content of How Can I Properly Stop a Goroutine's Execution After a Timeout in Go?. For more information, please follow other related articles on the PHP Chinese website!

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