- 模拟任务调度
- 同步(串行)任务/异步(并行)任务
- 遇到同步任务需执行完成后再执行后续任务
package main
import (
"context"
"fmt"
"sync"
"time"
)
func test(wg *sync.WaitGroup, ctx context.Context, jobId int) {
defer wg.Done()
for i := 0; i < 5; i++ {
select {
case <-ctx.Done():
fmt.Printf("任务Id:%d,异常退出\n", jobId)
return
default:
fmt.Printf("任务Id:%d,执行第%d次\n", jobId, i)
if jobId > 2 {
time.Sleep(time.Second * 5)
} else {
time.Sleep(time.Second * 2)
}
}
}
}
func main() {
ctx, cancel := context.WithCancel(context.Background())
wg := new(sync.WaitGroup)
go func() {
time.Sleep(time.Second * 20)
cancel()
}()
for i := 0; i < 5; i++ {
wg.Add(1)
go test(wg, ctx, i)
if i < 1 {
wg.Wait()
select {
case <-ctx.Done():
fmt.Println("main1 异常退出")
return
default:
fmt.Println("1 select")
}
}
}
wg.Wait()
select {
case <-ctx.Done():
fmt.Println("main2 异常退出")
return
default:
fmt.Println("2 select")
}
//测试阻塞
select {}
}