-2

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

icza
  • 389,944
  • 63
  • 907
  • 827
Murky
  • 21
  • 3

3 Answers3

4

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

icza
  • 389,944
  • 63
  • 907
  • 827
3

There are a few ways to tell if a goroutine has stopped.

  1. 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.
  2. Create a 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.
MahlerFive
  • 5,159
  • 5
  • 30
  • 40
1

Is there a way to detect if a go routine was interrupted while it was executing?

No.

Volker
  • 40,468
  • 7
  • 81
  • 87