我遇到了一个关于 goroutines 的问题。假设有一个通道,我们通过来自 main 的 goroutine 传递这个通道。现在,如果我们无法从 main 收听此频道(以防在收听之前发生返回/恐慌)。goroutine 不会停止。如果出现错误,如何停止这个 goroutine?
如果多次调用 goroutine 中的函数,例程的数量会不断增加。
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
}
}
}
输出:
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
.....继续这样增加
慕勒3428872
相关分类