您好,欢迎来到12图资源库!分享精神,快乐你我!我们只是素材的搬运工!!
  • 首 页
  • 当前位置:首页 > 开发 > WEB开发 >
    在 Go 言语中管理 Concurrency 的三种方式(3)
    时间:2020-08-12 12:07 来源:网络整理 作者:网络 浏览:收藏 挑错 推荐 打印

        cancel() //mock client exit, and pass the signal, ctx.Done() gets the signal  time.Sleep(3 * time.Second

        time.Sleep(3 * time.Second

     

    package main 

     

    import ( 

        "context" 

        "fmt" 

        "time" 

     

    func foo(ctx context.Context, name string) { 

        go bar(ctx, name) // A calls B 

        for { 

            select { 

            case <-ctx.Done(): 

                fmt.Println(name"A Exit"

                return 

            case <-time.After(1 * time.Second): 

                fmt.Println(name"A do something"

            } 

        } 

     

    func bar(ctx context.Context, name string) { 

        for { 

            select { 

            case <-ctx.Done(): 

                fmt.Println(name"B Exit"

                return 

            case <-time.After(2 * time.Second): 

                fmt.Println(name"B do something"

            } 

        } 

     

    func main() { 

        ctx, cancel := context.WithCancel(context.Background()) 

        go foo(ctx, "FooBar"

        fmt.Println("client release connection, need to notify A, B exit"

        time.Sleep(5 * time.Second

        cancel() //mock client exit, and pass the signal, ctx.Done() gets the signal  time.Sleep(3 * time.Second

        time.Sleep(3 * time.Second

    (责任编辑:admin)