如果我们无法通过传递给该例程的频道进行监听,如何停止goroutine

I have encountered an issue w.r.t goroutines. Suppose there is a channel and we passed this channel over a goroutine from main. Now if we fail to listen on this channel from main (in case a return/panic occur before listening). The goroutine doesn't stop. How to stop this goroutine in case of error?

In case of multiple call to the function in goroutine the number of routine keeps on increasing.

package main

import (
    "fmt"
    "runtime"
)

func test(a chan string) {
    defer func() {
        close(a)
        fmt.Println("channel close")
    }()
    fmt.Println("sending to channel")
    a <- "1"
    fmt.Println("sent to channel")
}

func method() string {

    fmt.Println("method starting no. of routine=>",
        runtime.NumGoroutine())
    b := make(chan string)

    go test(b)
    fmt.Println("method current no. of routine=>",
        runtime.NumGoroutine())

    return "error" //if this is executed the routines keeps on
    //increasing
    a := <-b
    return a
}

func main() {
    defer fmt.Println("final main no. of routine=>",
        runtime.NumGoroutine())
    i := 0
    //firing 10 request for method
    for {
        if i < 10 {
               fmt.Println(method())
               i++
        } else {
               break
        }

    }
}

Output:

method starting no. of routine=> 1

method current no. of routine=> 2

error

method starting no. of routine=> 2

method current no. of routine=> 3

error

method starting no. of routine=> 3

method current no. of routine=> 4

error

.....keeps on increasing like this

a routine can be stop by context. Before you use context, you should know only routine with loop are expected stop-control, those deadable routines are no need to stop.

context example:

func main(){
    ctx, cancel := context.WithCancel(context.Background())
    go func(c context.Context){
        for {
            select{
                case <-c.Done():
                   fmt.Println("exit success")
                default:
                   // service
                   fmt.Println("my logic service loop")
            }    
        }
    }(ctx)
    time.Sleep(5 * time.Second)
   cancel()
}