Skip to content

ants线程池使用

下载依赖:

go get github.com/panjf2000/ants/v2

使用示例:

golang
import (
    "fmt"
    "sync"
    "github.com/panjf2000/ants/v2"
)

// 任务参数
type TaskData struct {
	index int
	wg    *sync.WaitGroup
}

func main() {
    var swg sync.WaitGroup
    // 定义一个10个固定大小的线程池和执行任务的方法
    pool, _ := ants.NewPoolWithFunc(10, downloadTask)
    // 完成后释放线程池
    defer pool.Release()
    // for循环向线程池提交任务
    for index := min; index < max; index++ {
        swg.Add(1)
        // 执行任务方法的参数
        task := TaskData{index: index, wg: &swg}
        // 提交任务
        pool.Invoke(&task)
    }
    // 阻塞等待
    swg.Wait()

    // 所有任务完成后,再执行其他方法
    fmt.Println(">>>>")
}

// 线程池执行任务的方法
func downloadTask(data interface{}) {
    taskData := data.(*TaskData)
	fmt.Println(taskData.index)
	taskData.wg.Done()
}