Here is a certain function f() {for true {}} which is called from a program into a separate thread: go f() How to interrupt a running call when you repeatedly call go f() . Detailed example:

 func main(){ go getRedisBD() time.Sleep(time.Duration(10)*time.Minute) go getRedisBD() } func getRedisBD{ time.Sleep(time.Duration(3)*time.Minute) getRedisBD() } 

And now, after 10 minutes, you need to remove this function from the stream and run it.

  • Normal semaphore, not? - D-side
  • @ D-side: If you need not wait for the end, but just to check, a simple flag would probably come up with synchronization). - VladD
  • @VladD pah, the semaphore implies waiting. Yes, there is just an atomic flag. - D-side
  • I need to interrupt the execution of this thread - Oma
  • 2
    Give a minimal example of what you have and add to the question an exact description of what you want to do. - D-side

1 answer 1

It is impossible to interrupt the gorutin outside.

You can set some flag and check it inside the function or pass the channel as a parameter and write the value there when you need to interrupt the function.

But to check that the flag that the channel must the gorutina, which must be stopped. Only she herself can complete her execution.

The exception is os.Exit (...), but then the whole program stops at once, no defer, finalizers, etc. not called.

those.

 func f(){ for {} } 

you can not stop without the completion of the program entirely.

You can do something like

 package main import ( "fmt" "time" ) func main() { flag := false go f(&flag) time.Sleep(time.Second) flag = true time.Sleep(time.Second) fmt.Println(2) } func f(flag *bool) { for { if *flag { fmt.Println(1) return } } } 

Or so:

 package main import ( "fmt" "time" ) func main() { stop := make(chan bool) go f(stop) time.Sleep(time.Second) stop <- true time.Sleep(time.Second) fmt.Println(2) } func f(stop chan bool) { for { select { case <-stop: fmt.Println(1) return default: // Π’Π΅Ρ‚ΠΊΠ° default Π½ΡƒΠΆΠ½Π°, Ρ‡Ρ‚ΠΎΠ±Ρ‹ ΠΏΡ€ΠΈ отсутствии сообщСний Π² chan Ρ€Π°Π±ΠΎΡ‚Π° Ρ„ΡƒΠ½ΠΊΡ†ΠΈΠΈ ΠΏΡ€ΠΎΠ΄ΠΎΠ»ΠΆΠΈΠ»Π°ΡΡŒ вмСсто Π±Π»ΠΎΠΊΠΈΡ€ΠΎΠ²ΠΊΠΈ Π½Π° ΠΎΠΆΠΈΠ΄Π°Π½ΠΈΠΈ сообщСния } } }