原文鏈接:http://targetliu.com/2017/5/2...
很久沒有發過文章了 - -||,今天發一篇golang
中goroutine
相關的學習筆記吧,以示例爲主。html
WaitGroup
在 sync
包中,用於阻塞主線程執行直到添加的 goroutine
所有執行完畢。golang
Context
是在 Go1.7
中移入標準庫的。學習
Context
包不只實現了在程序單元之間共享狀態變量的方法,同時能經過簡單的方法,使咱們在被調用程序單元的外部,經過設置ctx變量值,將過時或撤銷這些信號傳遞給被調用的程序單元。線程
這是兩個有趣又實用的功能,在標準庫 time
包裏提供。code
<!--more-->htm
package main import ( "context" "fmt" "sync" "time" ) func main() { ch := make(chan int) //定義一個WaitGroup,阻塞主線程執行 var wg sync.WaitGroup //添加一個goroutine等待 wg.Add(1) //goroutine超時 go func() { //執行完成,減小一個goroutine等待 defer wg.Done() for { select { case i := <-ch: fmt.Println(i) //goroutine內部3秒超時 case <-time.After(3 * time.Second): fmt.Println("goroutine1 timed out") return } } }() ch <- 1 //新增一個1秒執行一次的計時器 ticker := time.NewTicker(1 * time.Second) defer ticker.Stop() //新增一個10秒超時的上下文 background := context.Background() ctx, _ := context.WithTimeout(background, 10*time.Second) //添加一個goroutine等待 wg.Add(1) go func(ctx context.Context) { //執行完成,減小一個goroutine等待 defer wg.Done() for { select { //每秒一次 case <-ticker.C: fmt.Println("tick") //內部超時,不會被執行 case <-time.After(5 * time.Second): fmt.Println("goroutine2 timed out") //上下文傳遞超時信息,結束goroutine case <-ctx.Done(): fmt.Println("goroutine2 done") return } } }(ctx) //等待全部goroutine執行完成 wg.Wait() }
1 tick tick tick goroutine1 timed out tick tick tick tick tick tick tick goroutine2 done