首页 >后端开发 >Golang >如何在超时后停止 Go Goroutine 执行?

如何在超时后停止 Go Goroutine 执行?

Barbara Streisand
Barbara Streisand原创
2024-12-24 11:21:15239浏览

How to Stop a Go Goroutine Execution After a Timeout?

超时停止 Goroutine 执行

在 Go 中,goroutine 提供了一种轻量级的并发执行代码的方法。然而,有时需要在特定时间后停止 goroutine。

问题:

用户遇到一个问题,即 goroutine 在超时后仍继续执行已设置。他们期望 Goroutine 在达到超时后立即停止,但相反,它打印了额外的消息。以下是示例代码:

type Response struct {
    data   interface{}
    status bool
}

func Find() (interface{}, bool) {
    ch := make(chan Response, 1)

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

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

预期输出:

  • 超时

实际输出:

  • 超时
  • 测试
  • test1

分析:

出现问题是因为通道的接收端设置了超时ch,不在发送端。虽然超时正确地识别出 50 毫秒内没有收到数据,但它并不能阻止 goroutine 进一步执行并随后在通道上发送数据。

解决方案:

由于在 Go 中不可能直接中断 goroutine 的执行,因此替代方法是需要:

  • 使用无缓冲的通道,它会阻止发送并强制 Goroutine 等待,直到通道准备好接收。
  • 使用带有取消的上下文并将其传递给 Goroutine。当超时发生时,取消上下文,goroutine 应该检查上下文并提前返回。
  • 使用自定义同步技术,例如互斥锁或等待组,来控制 goroutine 执行并确保及时终止。

以上是如何在超时后停止 Go Goroutine 执行?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn