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
Mary-Kate OlsenOriginal
2024-12-11 21:30:12969browse

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}
}()

The goroutine continues execution despite the timeout set in:

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

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
}

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:
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