Skip to content

Latest commit

 

History

History
59 lines (52 loc) · 838 Bytes

结合信号取消多个协程.md

File metadata and controls

59 lines (52 loc) · 838 Bytes
package main

import (
	"context"
	"os"
	"os/signal"
	"sync"
	"time"
)

type Work struct {
	c int //执行的协程数量
	n int //一共有多少任务需要执行
}

func (b *Work) runWorkers(ctx context.Context) {
	var wg sync.WaitGroup
	wg.Add(b.c)
	for i := 0; i < b.c; i++ {
		go func() {
			defer wg.Done()
			b.runWorker(ctx, b.n/b.c)
		}()
	}
	wg.Wait()
}

func (b *Work) runWorker(ctx context.Context, n int) {
	for i := 0; i < n; i++ {
		//监听取消
		select {
		case <-ctx.Done():
			return
		default:
			//TODO:: 需要执行的任务
			time.Sleep(time.Second)
		}
	}
}

func main() {
	w := &Work{
		c: 3,
		n: 30,
	}
	ctx, cancel := context.WithCancel(context.Background())
	//信号监听
	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt)
	go func() {
		<-c
		cancel()
	}()
	w.runWorkers(ctx)
}