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)

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

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效