Go从入门到实战——Context与任务取消(笔记)

关联任务的取消

在这里插入图片描述

Context

在这里插入图片描述

func isCancelled(ctx context.Context) bool {
	select {
	case <-ctx.Done():
		return true
	default:
		return false
	}
}

func TestCancel(t *testing.T) {
	ctx, cancel := context.WithCancel(context.Background())
	for i := 0; i < 5; i++ {
		go func(i int, ctx context.Context) {
			for {
				if isCancelled(ctx) {
					break
				}
				time.Sleep(time.Millisecond * 5)
			}
			fmt.Println(i, "Done")
		}(i, ctx)
	}
	cancel()
	time.Sleep(time.Second * 1)
}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_42094659/article/details/107737561
今日推荐