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)
}
}
}