我遇到了一個關于 goroutines 的問題。假設有一個通道,我們通過來自 main 的 goroutine 傳遞這個通道?,F在,如果我們無法從 main 收聽此頻道(以防在收聽之前發生返回/恐慌)。goroutine 不會停止。如果出現錯誤,如何停止這個 goroutine?如果多次調用 goroutine 中的函數,例程的數量會不斷增加。package mainimport ( "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=> 1method current no. of routine=> 2errormethod starting no. of routine=> 2method current no. of routine=> 3errormethod starting no. of routine=> 3method current no. of routine=> 4error.....繼續這樣增加
1 回答

慕勒3428872
TA貢獻1848條經驗 獲得超6個贊
例程可以根據上下文停止。在使用上下文之前,您應該知道只有帶有循環的例程才需要停止控制,那些死例程不需要停止。
上下文示例:
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()
}
- 1 回答
- 0 關注
- 139 瀏覽
添加回答
舉報
0/150
提交
取消