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

报告相同问题?

悬赏问题

  • ¥15 yolov8边框坐标
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂