How to kill go routine?

Hi guys I have a problem/question. How to kill go routine ?

My example code. I want kill the go routine in worker go routine.

Thanks.

package main

import (
	"time"
	"fmt"
	"runtime"
)

func worker(ch1 <-chan bool, ch2 <-chan int) {
	for {
		select {
		case <-ch2:
		// How to kill the go routine ?
			go func() {
				for {
					fmt.Println("Hıa")
					time.Sleep(0x2 * time.Second)
				}
			}()
		case <-ch1:
			goto Finish
		}
	}

Finish:
	fmt.Println("Closing go routine!")
	runtime.Goexit()
	return
}

func main() {
	ch1 := make(chan bool)
	ch2 := make(chan int)
	go worker(ch1, ch2)

	for i := 0x0; i <= 0xFF; i++ {
		if i == 0x5 {
			ch2 <- 1
		} else if i == 0xA {
			ch1 <- true
		} else {
			fmt.Println(i)
			time.Sleep(0x1 * time.Second)
		}
	}
}

The simplest answer is to write your code in a way that you can send a message to your goroutine telling it to exit. You have this already with your worker, but you don’t have it for your goroutines that it spawns. What I would suggest is to create a single channel inside of your worker that can be used to exit all of the spawned goroutines. Then when your worker function gets a message on ch1, it could then send a message out to its own exit channel telling those goroutines to terminate.

Here is a slightly tweaked version of your code that does this: https://play.golang.org/p/2H5mMKUeCj
Probably not the prettiest code but it is a quick and dirty example of what I mean.

1 Like

You can also use Context to cancel goroutines. (I prefer to set up explicit channels myself, though.)

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.