dongzhi6927 2016-06-23 16:56
浏览 64
已采纳

在无限循环中杀死方法(golang)

I am working with a piece of code that has an intentional infinite loop, I can't modify that code. I want to write some tests on that method (e.g. make sure it triggers actions at the right times) but I don't want to orphan a bunch of go routines. So I am trying to find a way that I can kill/interrupt that goroutine.

I was thinking of trying to wrap it in a wrapper function that would kill it after a signal. Like this (doesn't work).

func wrap(inf func()) func() {
  return func() {
    select {
    case inf():
    case <-time.After(5 * time.Second):
    }
  }
}

func main() {
  go wrap(inf())()
  // do things
}

All the variations I can think of don't really work. I was thinking of wrapping the inf in a function that writes to a channel (that will never get called), or something with a return statement. And then the select can read from that. The problem is then you have to launch that. If you do it in this routine you're never getting to the select. If you do it in another routine, you've just made the problem worse.

So, is there a way that I can kill that routine?

(yes - I would rather change the infinite loop code, but can't here)

  • 写回答

1条回答 默认 最新

  • doujingao6210 2016-06-23 17:18
    关注

    If you can't change the loop code, you can't kill the loop. Go is rather intentionally designed such that there's no way to kill a goroutine from outside of the goroutine, short of actually terminating the program itself.

    If you can change the loop itself, the typical method of killing a routine is to provide a quit channel to the goroutine, and then close (or send on) that channel to tell the loop to exit. Example:

    quitCh := make(chan struct{})
    go func() {
        for {
            select {
            case <-quitCh:
                return
            // other cases to handle what you need to do
            }
        }
    }()
    
    // Once you're done
    close(quitCh) // goroutine exits
    

    But without some way to coding that closure behavior into the loop itself, there's no way (to my knowledge) of specifically killing that goroutine or terminating the loop within it (unless you can trigger a panic in it, but that's a terrible way to handle that issue)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分