context結束子go程

fmt.Println("main 函數 開始...")
	go func() {
		ctx, cancel := context.WithCancel(context.Background())
		defer cancel()
		fmt.Println("父 協程 開始...")
		go func(ctx context.Context) {
			for {
				for {
					select {
					case <-ctx.Done():
						fmt.Println("子 協程 接受停止信號...")
						return
					default:
						fmt.Println("子 協程 執行中...")
						timer := time.NewTimer(time.Second * 2)
						<-timer.C
					}
				}
			}
		}(ctx)
		time.Sleep(time.Second*5)
		fmt.Println("父 協程 退出...")
	}()
	time.Sleep(time.Second*10)
	fmt.Println("main 函數 退出")

執行結果
main 函數 開始…
父 協程 開始…
子 協程 執行中…
子 協程 執行中…
子 協程 執行中…
父 協程 退出…
子 協程 接受停止信號…

main 函數 退出

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章