取消在Go中的阻塞操作

huangapple go评论92阅读模式
英文:

cancel a blocking operation in Go

问题

我有一个在我无法控制的第三方库中的阻塞操作。它有可能永远执行下去。所以我想在它上面设置一个超时。显而易见的方法是使用通道和 goroutine 来包装它,然后使用 time.After 在结果上进行选择。然而,问题是运行阻塞操作的 goroutine 有可能永远执行下去。

这里有一个示例来说明这个问题:http://repl.it/90o

有没有一种方法可以取消一个 goroutine 或者让它被垃圾回收?

英文:

I have a blocking operation in a 3rd party library that I don't control. It could potentially go forever. So I want to set a timeout on it. The obvious way is to wrap it with a channel and a goroutine and then select on the result with time.After. However, the problem is the goroutine running the blocking operation could potentially go forever.

Here is an example to illustrate this http://repl.it/90o

Is there a way to cancel a goroutine or have it garbage collected?

答案1

得分: 9

你无法从“外部”停止一个 goroutine。该 goroutine 必须支持某种终止信号(通常是一个通道)。但如果它不支持,你无法强制停止或杀死它。

如果你无法对你正在使用的第三方库做任何操作,你最多只能在一个不同的进程中运行它(在你的 Go 应用程序启动的不同应用程序中),然后你可以杀死该进程,但这只是一种不美观且过于繁琐的方法。

英文:

You can't stop a goroutine from the "outside". The goroutine has to support some kind of termination signalling (most often a channel). But if it does not, you can't force it or kill it.

If you can't do anything about the 3rd party lib you're using, the most that you could do is run it in a different process (in a different application started by your go app) which you can kill, but that is just ugly and too cumbersome.

答案2

得分: 0

我不认为你能做任何事情。在Go语言中,你无法从外部停止一个goroutine。如果你无法修复这个库,并且认为它可能会永远阻塞,那么你可以编写一个新的库来实现你想要的控制。

英文:

I don't think you can do anything. In Go you can't stop a goroutine from outside. If you can't fix this library and you think it could block forever, then write new one that you would be able to control.

huangapple
  • 本文由 发表于 2015年1月31日 00:18:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/28240133.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定