donglei1699 2019-02-01 08:22
浏览 27
已采纳

如果我们无法通过传递给该例程的频道进行监听,如何停止goroutine

I have encountered an issue w.r.t goroutines. Suppose there is a channel and we passed this channel over a goroutine from main. Now if we fail to listen on this channel from main (in case a return/panic occur before listening). The goroutine doesn't stop. How to stop this goroutine in case of error?

In case of multiple call to the function in goroutine the number of routine keeps on increasing.

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
        }

    }
}

Output:

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

.....keeps on increasing like this

  • 写回答

1条回答 默认 最新

  • doukangbin9698 2019-02-01 08:54
    关注

    a routine can be stop by context. Before you use context, you should know only routine with loop are expected stop-control, those deadable routines are no need to stop.

    context example:

    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()
    }
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法