Is there a way to detect if a go routine was interrupted while it was executing? I would like something similar to InterruptedException
in Java: https://docs.oracle.com/javase/8/docs/api/java/lang/InterruptedException.html
Is there a way to detect if a go routine was interrupted while it was executing?
No.
There are a few ways to tell if a goroutine has stopped.
sync.WaitGroup
and increment it by one. Pass the WaitGroup
to the goroutine. Inside the goroutine, defer calling Done()
on the WaitGroup
. Outside the goroutine you can call Wait()
on the WaitGroup
to know when it's finished.InterruptedException
in Java is thrown if the thread is interrupted e.g. with the Thread.interrupt()
method (while it is waiting, sleeping, or otherwise occupied).
In Go, you can't interrupt a goroutine from the outside (see cancel a blocking operation in Go), which means there is no sense talking about detecting it.
A goroutine may end normally if the function that is executed in a goroutine returns, or it may end abruptly if it panics. But even if it panics, that is due to its own function, and not because another goroutine forces it or interrupts it.
A goroutine can only be stopped if it self supports some kind of termination, e.g. it may monitor a channel which another goroutine may close (or send a value on it), which when detected the goroutine may return voluntarily–which will count as a normal termination (and not interruption).