go::context
1、context.WithCancel 2、context.WithDeadline 3、context.WithTimeout 4、context.WithValue
1. WithCancel()函数接受一个 Context 并返回其子Context和取消函数cancel 2. 新创建协程中传入子Context做参数,且需监控子Context的Done通道,若收到消息,则退出 3. 需要新协程结束时,在外面调用 cancel 函数,即会往子Context的Done通道发送消息 4. 当 父Context的 Done() 关闭的时候,子 ctx 的 Done() 也会被关闭
var wg = sync.WaitGroup{} func cpuInfo(ctx context.Context){ defer wg.Done() for { select { case <- ctx.Done(): fmt.Println("监控退出") return default: time.Sleep(time.Second) fmt.Println("获取cpu信息成功") } } } func main() { wg.Add(1) ctx, cancel := context.WithCancel(context.Background()) //ctx, cancel := context.WithTimeout(context.Background(), time.Second*3) //ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(2* time.Second)) //ctx := context.WithValue(context.Background(), string("hello"), "hello") go cpuInfo(ctx) time.Sleep(time.Second*6) cancel() wg.Wait() }