/* * @Author: Casso-Wong * @Date: 2021-06-21 18:16:18 * @Last Modified by: Casso-Wong * @Last Modified time: 2021-06-21 18:16:18 */ package main import ( "context" "fmt" "sync" "time" ) var wg sync.WaitGroup func main() { wg.Add(1) // 自定义一个context,context需要基于一个parent context ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) // 这里预操作 cancel context defer cancel() // 起示例 goroutine go func(c context.Context) { EXIT: for { // 模拟一些超时操作,主要是根据:<-ctx.Done() 来及时返回函数,达到控制 goroutine 生命周期的目的 select { case <-ctx.Done(): // 超时直接返回,销毁 goroutine fmt.Println("context time out") break EXIT default: fmt.Println("do something") } } wg.Done() }(ctx) wg.Wait() fmt.Println("other goroutines are compeleted with time-out, now stop main goroutine") }