[英]How to stop a goroutine if we fail to listen from a channel passed to that routine
我遇到了wrt 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
.....保持這樣的增長
例程可以根據上下文而停止。 在使用上下文之前,應該知道只有帶有循環的例程才是停止控制,那些可破壞的例程無需停止。
上下文示例:
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()
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.