猿问

如果我们无法从传递给该例程的通道收听,如何停止 goroutine

我遇到了一个关于 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

.....继续这样增加


达令说
浏览 101回答 1
1回答

慕勒3428872

例程可以根据上下文停止。在使用上下文之前,您应该知道只有带有循环的例程才需要停止控制,那些死例程不需要停止。上下文示例:func main(){&nbsp; &nbsp; ctx, cancel := context.WithCancel(context.Background())&nbsp; &nbsp; go func(c context.Context){&nbsp; &nbsp; &nbsp; &nbsp; for {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; select{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; case <-c.Done():&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;fmt.Println("exit success")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; default:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// service&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;fmt.Println("my logic service loop")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }(ctx)&nbsp; &nbsp; time.Sleep(5 * time.Second)&nbsp; &nbsp;cancel()}
随时随地看视频慕课网APP

相关分类

Go
我要回答