如何管理 Go 例程并停止特定的 Go 例程

发布于 2025-01-14 17:14:34 字数 566 浏览 4 评论 0原文

这是真实情况的抽象示例,我必须通过调用 func B (func A)来停止由 func A 创建的某些特定 go 例程

func A(context, interval, ...params) {
 go (interval) {
    tk := time.ticker(interval)
    for {
      select {
       case <- tk.C:
        err := func C(params)
     }
    }
  }(interval)
}

(func A)使用特定参数以重复间隔创建 go 例程执行(func C)。

func B(context, ...params) {
  // stop go routine that runs func C with specific params.
}

(func B) 需要使用给定参数停止 go 例程运行 (func C)。 另外,我如何处理(func A)中的错误和上下文超时等情况。

注意:提供了伪代码,抱歉无法共享真实代码。

This is an abstract example to real case, I have to stop some specific go routine created by a func A by calling func B

func A(context, interval, ...params) {
 go (interval) {
    tk := time.ticker(interval)
    for {
      select {
       case <- tk.C:
        err := func C(params)
     }
    }
  }(interval)
}

(func A) creates go routine executing (func C) at repeated interval with specific parameters.

func B(context, ...params) {
  // stop go routine that runs func C with specific params.
}

(func B) needs to stop go routine running (func C) with given parameters.
Also how can I handle cases like error and context timeout in (func A).

note: pseudo code provided, sorry real code cannot be shared.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

不离久伴 2025-01-21 17:14:34

我相信您正在寻找 context.Done

Done 返回一个通道,当应取消代表此上下文完成的工作时,该通道已关闭。

select {
case <-ctx.Done():
    // context was cancelled, stop goroutine
    return
case <-tk.C:
    C(params...)
}

工作示例: https://go.dev/play/p/wSUHSHCse7D< /a>

没有简单的方法可以根据参数查找 goroutine,因此您必须稍微调整代码以选择要取消的上下文。

I believe you're looking for context.Done.

Done returns a channel that's closed when work done on behalf of this context should be canceled.

select {
case <-ctx.Done():
    // context was cancelled, stop goroutine
    return
case <-tk.C:
    C(params...)
}

Working example: https://go.dev/play/p/wSUHSHCse7D

There is no simple way of finding goroutine based on params so you have to adjust your code a little bit to select which context you want to cancel.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文