Context與任務的取消
===
一個任務有起了多個子任務

- 根Context: 通過context.Background() 創建
- 子`Context context.WithCancel(父context)`創建
- `ctx, cancel := context.WithCancel(context.Background())`
- 當前Context被取消時,基于他的子context都會被取消
- 接受取消通知`<-ctx.Done()`
~~~
func TestService(t *testing.T) {
dataCh := make(chan int,10)
end := make(chan bool)
ctx, cancel := context.WithCancel(context.Background())
go production(dataCh,cancel)
go consume(ctx,dataCh,end)
<-end
}
// 生產者
func production(ch chan int,cancelFunc context.CancelFunc) {
for i:=0;i<1000;i++{
ch<-i
}
cancelFunc()
}
// 消費者
func consume(ctx context.Context,ch chan int,end chan bool) {
forloop:
for {
select {
case data := <-ch:
fmt.Println(data)
case <-ctx.Done():
fmt.Println("end------------------")
break forloop
}
}
end<-true
}
~~~
這個例子沒有舉好,大家先知道怎么用
- Hello World
- UDP
- UDP服務端
- UDP客戶端
- UDP廣播
- 錯誤處理
- 編寫好的異常處理
- panic和recover
- 并發編程
- Hello Goruntine
- 共享內存并發機制
- RWMutex
- CSP并發機制
- 多路復用和超時控制
- 通道關閉與廣播
- Context與任務的取消
- 只運行一次
- 按需任意任務完成
- 所有任務完成
- 補充:range channel注意實現
- 對象池
- sync.Pool臨時對象池
- 單元測試
- 表格測試法
- Banchmark
- BDD
- 反射
- 利用反射編寫靈活的代碼
- Struct Tag
- 萬能程序
- 常用架構模式
- Pipe-filter pattern
- Micro Kernel
- 性能分析
- 高性能代碼
- sync.MAP分析
- Concurrent Map
- GC友好的代碼
- Uber開發風格規范