go协程的2+1
go协程使用心得-go协程的2+1
go协程只做两件事:执行逻辑函数、监听执行状态并且控制流程
1 func TestCtx(t *testing.T) { 2 ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) 3 defer cancel() 4 5 res := make([]string, 0) 6 mutex := sync.Mutex{} 7 go func() { // 监听状态,控制流程 8 wg := sync.WaitGroup{} 9 for i := 0; i < 100000; i++ { 10 wg.Add(1) 11 go func() { // 监听状态,控制流程 12 defer wg.Done() 13 14 cc, cCancel := context.WithCancel(ctx) 15 defer cCancel() 16 17 ch := make(chan string, 1) 18 go func() { // 执行逻辑代码 19 // todo logic code... 20 time.Sleep(2 * time.Second) 21 ch <- "" 22 }() 23 24 select { 25 case <-cc.Done(): // 超时直接退出 26 return 27 case a := <-ch: 28 mutex.Lock() 29 defer mutex.Unlock() 30 res = append(res, a) // 完成任务塞入slice 31 } 32 }() 33 } 34 wg.Wait() // 正常或非正常完成,退出主context 35 cancel() 36 }() 37 38 select { 39 case <-ctx.Done(): 40 fmt.Println(len(res)) 41 return 42 } 43 }