dter8514 2019-03-30 00:07
浏览 402

goroutine不尊重`ctx.done()`或正确退出

I am trying to achieve quit gracefully when user press Ctrl-C. I am trying the code in Make Ctrl+C cancel the context.Context. package main

import (
    "context"
    "fmt"
    "os"
    "os/signal"
    "time"
)

func main() {

    ctx := context.Background()

    // trap Ctrl+C and call cancel on the context
    ctx, cancel := context.WithCancel(ctx)
    c := make(chan os.Signal, 1)
    signal.Notify(c, os.Interrupt)
    defer func() {
        signal.Stop(c)
        cancel()
        fmt.Println("Cleaned up")
    }()
    go func() {
        select {
        case <-c:
            fmt.Println("Got interrupt signal")
            cancel()
        case <-ctx.Done():
        }
        fmt.Println("Stopped monitoring")
    }()
    select {
    case <-ctx.Done():
        fmt.Println("notified to quit")
    case <-time.NewTimer(time.Second * 2).C:
        fmt.Println("done something")
    }
}

It works well as expected when user press Ctrl-c, it console out the following:

Got interrupt signal
Stopped monitoring
notified to quit
Cleaned up

However, if it quit normally, It doesn't work as expected as below:

done something
Cleaned up

I mean it should print out Stopped monitoring, but not. In defer cleanup function, it called cancel() which should trigger the select in monitoring goroutine to quit, but not.

How to solve the issue?

  • 写回答

1条回答 默认 最新

  • duanke6249 2019-03-30 05:49
    关注

    Thanks @Zan Lynx, I worked out the below solution.

    package main
    
    import (
        "context"
        "fmt"
        "os"
        "os/signal"
        "time"
    )
    
    func main() {
        ctx := context.Background()
        ctx, cancel := context.WithCancel(ctx)
        terminated := monitor(ctx, cancel)
        defer func() {
            cancel()
            fmt.Println("Cleaned up")
            <-terminated // wait for the monior goroutine quit
        }()
        select {
        case <-ctx.Done():
            fmt.Println("notified to quit")
        case <-time.NewTimer(time.Second * 1).C:
            fmt.Println("done something")
        }
    }
    
    func monitor(ctx context.Context, cancel context.CancelFunc) <-chan interface{} {
        c := make(chan os.Signal, 1)
        signal.Notify(c, os.Interrupt)
        terminated := make(chan interface{})
        go func() {
            defer close(terminated)
            defer fmt.Println("Stopped monitoring1")
            defer signal.Stop(c)
            select {
            case <-c:
                fmt.Println("Got interrupt singnal")
                cancel()
            case <-ctx.Done():
            }
        }()
        return terminated
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 任务A:大数据平台搭建(容器环境)怎么做呢?
  • ¥15 r语言神经网络自变量重要性分析
  • ¥15 基于双目测规则物体尺寸
  • ¥15 wegame打不开英雄联盟
  • ¥15 公司的电脑,win10系统自带远程协助,访问家里个人电脑,提示出现内部错误,各种常规的设置都已经尝试,感觉公司对此功能进行了限制(我们是集团公司)
  • ¥15 救!ENVI5.6深度学习初始化模型报错怎么办?
  • ¥30 eclipse开启服务后,网页无法打开
  • ¥30 雷达辐射源信号参考模型
  • ¥15 html+css+js如何实现这样子的效果?
  • ¥15 STM32单片机自主设计