Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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?

like image 461
Amjad Masad Avatar asked Jan 30 '15 16:01

Amjad Masad


People also ask

How do I cancel my GoRoutine?

You can't kill a goroutine from outside. You can signal a goroutine to stop using a channel, but there's no handle on goroutines to do any sort of meta management. Goroutines are intended to cooperatively solve problems, so killing one that is misbehaving would almost never be an adequate response.

Is Select blocking in GO?

If there is no default case, the "select" statement blocks until at least one of the communications can proceed. So, without a default case, the code will block until some data is available in either of the channels. It implicitly waits for the other goroutines to wake up and write to their channel.

Is Go blocking or non blocking?

Go can and does use only blocking calls because everything runs in goroutines and they're not real OS threads.


1 Answers

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.

like image 148
icza Avatar answered Sep 28 '22 08:09

icza