簡言
1. context包的WithTimeout()函數接受一個 Context 和超時時間作為參數,返回其子Context和取消函數cancel
2. 新創建協程中傳入子Context做參數,且需監控子Context的Done通道,若收到消息,則退出
3. 需要新協程結束時,在外面調用 cancel 函數,即會往子Context的Done通道發送消息
4. 若不調用cancel函數,到了原先創建Contetx時的超時時間,它也會自動調用cancel()函數,即會往子Context的Done通道發送消息
實驗步驟
1. 利用根Context創建一個父Context,使用父Context創建2個協程,超時時間設為3秒
2. 等待8秒鍾,再調用cancel函數,其實這個時候會發現在3秒鍾的時候兩個協程已經收到退出信號了
實驗結果如下圖
package main import ( "context" "fmt" "time" ) func main() { // 創建一個子節點的context,3秒后自動超時 ctx, cancel := context.WithTimeout(context.Background(), time.Second*3) go watch(ctx, "監控1") go watch(ctx, "監控2") fmt.Println("現在開始等待8秒,time=", time.Now().Unix()) time.Sleep(8 * time.Second) fmt.Println("等待8秒結束,准備調用cancel()函數,發現兩個子協程已經結束了,time=", time.Now().Unix()) cancel() } // 單獨的監控協程 func watch(ctx context.Context, name string) { for { select { case <-ctx.Done(): fmt.Println(name, "收到信號,監控退出,time=", time.Now().Unix()) return default: fmt.Println(name, "goroutine監控中,time=", time.Now().Unix()) time.Sleep(1 * time.Second) } } }