版权声明 本站原创文章 由 萌叔 发表
转载请注明 萌叔 | http://vearne.cc

引言

很多时候,还是需要用到协程池的,简单撸了一个,方便工作中的需要,有bug请反馈

1. 安装

go get github.com/vearne/golib/utils

2. 使用

2.1 创建协程池

// 协程池的大小是30
var p *utils.GPool = utils.NewGPool(30)

2.2 定义任务处理函数

任务处理函数形如

type JobFunc func(param interface{}) *GPResult

GPResult

type GPResult struct {
	Value interface{}
	Err   error
}

执行任务

ApplyAsync(f JobFunc, slice []interface{})

示例

pool.go

package main

import (
	"github.com/vearne/golib/utils"
	"log"
	"strconv"
)

func Judge(key interface{}) *utils.GPResult {
	result := &utils.GPResult{}
	num, _ := strconv.Atoi(key.(string))
	if num < 450 {
		result.Value = true
	} else {
		result.Value = false
	}
	return result
}

func main() {
	p := utils.NewGPool(30)

	slice := make([]interface{}, 0)
	for i := 0; i < 1000; i++ {
		slice = append(slice, strconv.Itoa(i))
	}

	result := make([]bool, 0, 10)
	trueCount := 0
	falseCount := 0
	for item := range p.ApplyAsync(Judge, slice) {
		value := item.Value.(bool)
		result = append(result, value)
		if value {
			trueCount++
		} else {
			falseCount++
		}
	}

	log.Printf("cancel, %v, true:%v, false:%v\n", len(result), trueCount, falseCount)
}

致谢

程序的API形式以及思路参考了python的multiprocessing模块,再此表示感谢


请我喝瓶饮料

微信支付码