cancel a blocking operation in Go

2020-01-23 12:47发布

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?

2条回答
爷、活的狠高调
2楼-- · 2020-01-23 13:30

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.

查看更多
爷的心禁止访问
3楼-- · 2020-01-23 13:33

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.

查看更多
登录 后发表回答