package main
import (
"fmt"
"time"
)
type Task struct {
f func() error
}
func (t Task) exec() error {
return t.f()
}
func NewTask(fun func() error) *Task {
return &Task{
f: fun,
}
}
type Pool struct {
JobChannel chan *Task
EntryChannel chan *Task
WorkerNum int
}
func NewPool(workerNum int) *Pool {
return &Pool{
JobChannel: make(chan *Task),
EntryChannel: make(chan *Task),
WorkerNum: workerNum,
}
}
func (p *Pool) run() {
//开启数量工作协池池
for i := 0; i < p.WorkerNum; i++ {
go p.worker(i)
}
//将进入的任务压入job
for task := range p.EntryChannel {
p.JobChannel <- task
}
}
func (p *Pool) worker(workId int) {
for v := range p.JobChannel {
fmt.Println("workId", workId)
v.exec()
}
}
func main() {
// 创建一个协程池,最大开启两个协程worker
p := NewPool(5)
// 开启一个协程,向Pool中发送10个task任务
go func() {
for i := 0; i < 20; i++ {
p.EntryChannel <- NewTask(func() error {
fmt.Println("创建一个Task:", time.Now().Format("2006-01-02 15:04:05"))
return nil
})
}
defer close(p.EntryChannel)
}()
// 启动协程池
p.run()
time.Sleep(1000)
}
标签:Task,JobChannel,WorkerNum,chan,golang,协程池,func,Pool From: https://www.cnblogs.com/jichenghui/p/18069415