首页 > 其他 > 详细

使用context关闭协程以及协程中的协程

时间:2018-10-24 13:37:46      阅读:125      评论:0      收藏:0      [点我收藏+]
package main

import (
    "sync"
    "context"
    "fmt"
    "time"
)

var wg sync.WaitGroup

func worker2(ctx context.Context) {
    LOOP:
        for {
            fmt.Printf("worker2\n")
            time.Sleep(time.Second)
            select {
            case <- ctx.Done():
                break LOOP
            default:
            }
        }
}


func worker(ctx context.Context) {
    go worker2(ctx)
    LOOP:
        for {
            fmt.Printf("worker\n")
            time.Sleep(time.Second)
            select {
            case <- ctx.Done():
                break LOOP
            default:

            }
        }
    wg.Done()
}

func main() {
    ctx := context.Background()
    ctx, cancel := context.WithCancel(ctx)
    wg.Add(1)
    go worker(ctx)
    //time.Sleep(time.Second*3)
    cancel()
    wg.Wait()
}

使用context关闭协程以及协程中的协程

原文:https://www.cnblogs.com/Csir/p/9842537.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!