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