package main
import "fmt"
type Task struct {
doSth func() error
}
func NewTask(taskFunc func() error) (task *Task){
task=&Task{
doSth:taskFunc,
}
return
}
func (t *Task)Execute() {
t.doSth()
}
//
type Pool struct {
entryChannel chan *Task
workerNum int
jobsChannel chan *Task
}
func NewPool(cap int) (pool *Pool ){
pool=&Pool{
entryChannel:make(chan *Task),
workerNum:cap,
jobsChannel:make(chan *Task),
}
return
}
func (p *Pool)Worker(workerId int) {
for task:=range p.jobsChannel {
task.Execute()
}
}
func (p *Pool)Run() {
for i:=0;i<p.workerNum;i++ {
go p.Worker(i)
}
for task:=range p.entryChannel {
p.jobsChannel<-task
}
close(p.jobsChannel)
close(p.entryChannel)
}
func main() {
t:=NewTask(func() error {
fmt.Println("123")
return nil
})
t2:=NewTask(func() error {
fmt.Println("456")
return nil
})
pool:=NewPool(3)
go func() {
for {
pool.entryChannel<-t
pool.entryChannel<-t2
}
}()
pool.Run()
}
网友评论