亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如果我們無法從傳遞給該例程的通道收聽,如何停止 goroutine

如果我們無法從傳遞給該例程的通道收聽,如何停止 goroutine

Go
達令說 2023-06-05 16:56:23
我遇到了一個關于 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()

}


查看完整回答
反對 回復 2023-06-05
  • 1 回答
  • 0 關注
  • 139 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號