Go並發控制--context的使用
阿新 • • 發佈:2018-06-19
el函數 text one ask Go default with block main
並發控制 Cancel Example
通過使用WithCancel可以取消一個或多個goroutine的執行,以實現對並發的控制。
package main import ( "context" "fmt" "time" ) func PrintTask(ctx context.Context) { for { select { case <- ctx.Done(): return default: time.Sleep(2*time.Second) fmt.Println("A man must walk down many roads.") } } } func main() { ctx := context.Background() ctx, cancel := context.WithCancel(ctx) defer cancel() go PrintTask(ctx) go PrintTask(ctx) go PrintTask(ctx) time.Sleep(3*time.Second) fmt.Println("main exit...") }
WithCancel返回cancel函數,調用cancel函數會關閉Done channel,PrintTask就會結束。
output
A man must walk down many roads.
A man must walk down many roads.
A man must walk down many roads.
main exit...
並發超時控制 Timeout Example
WithTimeout可以實現並發超時控制,使goroutine執行超時時自動結束。
package main import ( "context" "fmt" "time" ) func main() { ctx := context.Background() timeout := 50*time.Millisecond ctx, cancel := context.WithTimeout(ctx, timeout) defer cancel() done := make(chan int,1) go func() { // do something time.Sleep(1*time.Second) done<- 1 }() select{ case <-done: fmt.Println("work done on time") case <-ctx.Done(): // timeout fmt.Println(ctx.Err()) } fmt.Println("main exit...") }
output:
context deadline exceeded
main exit...
Go並發控制--context的使用