golang goroutine 骚操作系列 CallerRunsPolicy
func taskQueueJob(id int, wg *sync.WaitGroup, ch chan struct{}, maxChan chan struct{}) {
defer func() {
<-ch // 任务完成后从通道中取出一个元素
<-maxChan
wg.Done()
}()
task(id)
}
func task(id int) {
fmt.Printf("Task %d is running...\n", id)
time.Sleep(1 * time.Second)
fmt.Printf("Task %d has been completed\n", id)
}
func main() {
taskQueue := make(chan struct{}, 10)
maxTask := make(chan struct{}, 2)
wg := sync.WaitGroup{}
for i := 1; i <= 15; i++ {
select {
case taskQueue <- struct{}{}:
maxTask <- struct{}{}
wg.Add(1)
go taskQueueJob(i, &wg, taskQueue, maxTask)
default:
fmt.Printf("Task %d is executed by the main process\n", i)
task(i)
}
}
close(taskQueue)
wg.Wait()
close(maxTask)
}
本作品采用《CC 协议》,转载必须注明作者和本文链接
推荐文章: