美文网首页
golang context提前退出

golang context提前退出

作者: darcyaf | 来源:发表于2020-04-04 13:12 被阅读0次

    golang中context包实现提前退出
    以前不知道怎么写的,一直无法退出,还以为程序就是无法提前退出。。
    下面的程序,request休眠100s,然后在另外一个goroutine中,3s后退出所有context

    import (
        "context"
        "log"
        "sync"
        "time"
    )
    
    func request() {
        time.Sleep(100 * time.Second)
    }
    
    var wg sync.WaitGroup
    
    func do(ctx context.Context,wg *sync.WaitGroup, f func())  {
        defer wg.Done()
        ctx2, cancel2 := context.WithCancel(ctx)
        defer cancel2()
        var ch = make(chan struct{})
        go func() {
            f()
            close(ch)
        }()
        select {
        case <-ctx2.Done():
            log.Println("提前结束")
        case <-ch:
            log.Println("任务完成")
        }
    }
    func main() {
        ctx, cancel := context.WithCancel(context.TODO())
        wg.Add(1)
        go do(ctx, &wg, request)
        go func() {
            time.Sleep(3 * time.Second)
            cancel()
        }()
        wg.Wait()
    }
    
    

    相关文章

      网友评论

          本文标题:golang context提前退出

          本文链接:https://www.haomeiwen.com/subject/kebdphtx.html