dongmu5815 2016-09-22 07:33
浏览 25
已采纳

如何关闭运行基于流的逻辑的goroutine?

I have some goroutine logics like this:

go func() {
    do_things_0()
    do_things_1()
    do_things_2()
    do_things_3()
    ...
    ...
} ()

When the service receives a request, it will create such goroutine. And the goroutine maybe memory consuming and needs to run more than 30 minutes.

Sometimes, the service may notice the lack of memory, and needs to terminate some goroutines.

My questions are:

  1. How can I terminate the goroutine in the above example?
  2. Is there any way to know the used memory of each goroutine?

Update

  1. I read other SO answers that goroutine can't be killed outside
  2. I suppose that send a signal to the channel handled by the goroutine to make the goroutine quit is only suitable for the for loop based logics.
  3. I am looking for some best practice to close the goroutine for the flow based logics.
  • 写回答

1条回答 默认 最新

  • dqppv86022 2016-11-29 21:41
    关注

    You should be able to adapt this easily to a for loop if you range over a list of the functions that are your steps:

    package main
    
    import (
        "fmt"
        "time"
    )
    
    func a() { fmt.Printf("a") }
    func b() { fmt.Printf("b") }
    func c() { fmt.Printf("c") }
    func d() { fmt.Printf("d") }
    func e() { fmt.Printf("e") }
    
    func f(quit <-chan struct{}) {
        for i := 0; i < 10000; i++ {
            for _, fn := range []func(){a, b, c, d, e} {
                select {
                case _, _ = <-quit:
                    fmt.Println("quit f")
                    return
                default:
                    fn()
                    time.Sleep(1 * time.Millisecond)
                }
            }
        }
    }
    
    func main() {
        quit := make(chan struct{})
        fmt.Println("go f")
        go f(quit)
        fmt.Println("sleep")
        time.Sleep(100 * time.Millisecond)
        fmt.Println("
    quit")
        close(quit)
        time.Sleep(10 * time.Millisecond)
        fmt.Println("exit")
    }
    

    Try it on the playground.

    The outer loop is just there to repeat the steps for long enough that we can witness the quit command happening.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么