简体   繁体   English

在Go中取消阻止操作

[英]cancel a blocking operation in Go

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 . 最明显的方法是用一个通道和一个goroutine包装它,然后用time.After选择结果。 However, the problem is the goroutine running the blocking operation could potentially go forever. 但是,问题是运行阻塞操作的goroutine可能永远消失。

Here is an example to illustrate this http://repl.it/90o 这是一个示例来说明此http://repl.it/90o

Is there a way to cancel a goroutine or have it garbage collected? 有没有办法取消goroutine或将其收集为垃圾?

You can't stop a goroutine from the "outside". 您无法从“外部”停止goroutine。 The goroutine has to support some kind of termination signalling (most often a channel). goroutine必须支持某种终止信令(通常是信道)。 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. 如果您对正在使用的第三方库无能为力,那么您最大可能要做的就是在一个可以杀死的不同进程(在由go应用启动的另一个应用程序中)中运行它,但这仅仅是丑陋又太笨重。

I don't think you can do anything. 我认为您无能为力。 In Go you can't stop a goroutine from outside. 在Go中,您无法从外部停止goroutine。 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. 如果您无法修复该库,并且认为它可能永远受阻,请编写一个您可以控制的新库。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM