3

I would like to know how to kill/stop goroutines. All examples are based on channels and select, which seems to only work if the goroutine contains some repeating task between which it can listen on a channel. Is there a way to stop the below goroutine before it returns?

package main

import (
        "time"
)

func main() {
    stop := make(chan string, 1)

    go func() {
        time.Sleep(10 * time.Second)
        stop <- "stop"
        return
    }()
    <- stop
}
André Betz
  • 1,291
  • 2
  • 10
  • 9

1 Answers1

4

Is there a way to stop the below goroutine before it returns?

No there is not (except calling os.Exit to abort the whole program).

Goroutines are self-contained and not controllable from the outside.

Volker
  • 40,468
  • 7
  • 81
  • 87