Golang Context的常规操作

Golang Context的常规操作

context

context是go的并发编程的常用模式,可以通过context来处理超时,取消任务等一系列操作

用context 取消任务

示例

func main() {
	parentCtx, cancel := context.WithCancel(context.Background())

	for i := 0; i < 10; i++ {//启动10个goroutine
		childCtx, _ := context.WithCancel(parentCtx)//创建子的context
		go func(ctx context.Context, index int) {
			for {
				select {
				case <-ctx.Done():
					fmt.Println("goroutine done:", index)
					return
				}
			}

		}(childCtx, i)
	}
	<-time.After(time.Second * 2)//2秒后开始关闭
	cancel()//关掉paraentContext,会引发所有子的context被关闭
	time.Sleep(time.Second)//sleep 1秒为了能观察10个goroutine的推出情况
	return
	}

输出结果

goroutine done: 2
goroutine done: 4
goroutine done: 3
goroutine done: 8
goroutine done: 1
goroutine done: 7
goroutine done: 6
goroutine done: 9
goroutine done: 0
goroutine done: 5

超时任务处理

未完待续…

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值