[go学习笔记]二十六、go语言中的Context与任务取消

194 阅读1分钟

更多学习笔记和示例代码请访问:github.com/wenjianzhan…

Context

  • 根 Context:通过 context.Background() 创建
  • 子 Context:context.WithCancel(parentContext) 创建
  • ctx, cancel := context.WithCancel(context.Background())
  • 当前 Context 被取消时,基于他的子 context 都会被取消
  • 接收取消通知 <-ctx.Done()
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, "Cancelled")

		}(i, ctx)
	}
	cancel()
	time.Sleep(time.Second * 1)
}

输出

=== RUN   TestCancel
1 Cancelled
0 Cancelled
4 Cancelled
3 Cancelled
2 Cancelled
--- PASS: TestCancel (1.00s)
PASS

Process finished with exit code 0

更多学习笔记和示例代码请访问:github.com/wenjianzhan…