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
-
How would a goroutine be interrupted? – Jonathan Hall Feb 03 '19 at 20:03
-
See this answer for a discussion of how a goroutine might be stopped https://stackoverflow.com/questions/6807590/how-to-stop-a-goroutine (corrected link) – Vorsprung Feb 03 '19 at 20:48
-
It really depends on what you mean by "interrupted". Interruption like you're referring to from Java does not happen in Go. – Adrian Feb 04 '19 at 15:05
3 Answers
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).

- 389,944
- 63
- 907
- 827
There are a few ways to tell if a goroutine has stopped.
- Pass a channel to the goroutine. Inside the goroutine, defer closing the channel. Outside the goroutine, you can wait for the channel to be closed.
- Create a
sync.WaitGroup
and increment it by one. Pass theWaitGroup
to the goroutine. Inside the goroutine, defer callingDone()
on theWaitGroup
. Outside the goroutine you can callWait()
on theWaitGroup
to know when it's finished.

- 5,159
- 5
- 30
- 40
Is there a way to detect if a go routine was interrupted while it was executing?
No.

- 40,468
- 7
- 81
- 87