golang并发ants和context取消通知demo

package main

import (
	"context"
	"fmt"
	"github.com/panjf2000/ants/v2"
	"time"
)
/*
	test ants&context demo
	@kingram
 */

type Task struct {
	index int
}

func (t *Task) Do() {
	fmt.Println("do...",t.index)
}

func taskFunc(data interface{}) {
	task := data.(*Task)
	task.Do()
}

func main() {
	ctx, cancel :=context.WithCancel(context.Background())
	go t(ctx)

	time.Sleep(time.Second * 10)
	cancel()
	select {}
}

func t(ctx context.Context) {
	p, _ := ants.NewPoolWithFunc(100, taskFunc)
	defer p.Release()

	i := 0
	for {
		select {
		case <-ctx.Done():
			fmt.Println("cancel()....")
			return
		default:
			i++
			task := &Task{
				index:  i,
			}
			p.Invoke(task)
		}
	}
}

posted @ 2021-12-01 23:16  Kingram  阅读(478)  评论(0编辑  收藏  举报