go ants使用

发布时间 2023-11-21 22:48:38作者: 潜行1

NewPoolWithFunc -> func(data interface{}) -> data.(Task) -> Task.Do

上面的这些函数都是同步的,添加到 NewPoolWithFunc中后,执行 invoke会变成异步

NewPool和NewPoolWithFunc本质是一样的,都是一个 anonymous function

参考demo,人家的代码抽象能力比我强得多

func main() {
	p, _ := ants.NewPoolWithFunc(10, taskFunc)
	defer p.Release()

	p.Invoke()
}

// 直接添加到goroutine的函数
func taskFunc(data interface{}) {
	task := data.(*Task)
	task.Do()
	fmt.Printf("task:%d sum:%d\n", task.index, task.sum)
}

// 对并发任务的抽象
type Task struct {
	index int
	nums  []int
	sum   int
	wg    *sync.WaitGroup
}

func (t *Task) Do() {
	for _, num := range t.nums {
		t.sum += num
	}
	t.wg.Done()
}