package main
import (
"fmt"
"runtime"
"time"
)
type Task struct {
f func() error
}
func NewTask(task func() error) *Task {
t := Task{
f: task,
}
return &t
}
func (t *Task) Execute() {
t.f()
}
type Pool struct {
EntryChannel chan *Task
JobsChannel chan *Task
workerNum int
}
func NewPool() *Pool {
numCpu := runtime.NumCPU()
p := &Pool{
EntryChannel: make(chan *Task),
JobsChannel: make(chan *Task),
workerNum: numCpu,
}
return p
}
func (p *Pool) worker(workerID int) {
for task := range p.JobsChannel {
fmt.Printf("worker ID[%d] exectuing ", workerID)
task.Execute()
fmt.Printf("worker ID[%d] exec end\n", workerID)
}
}
func (p *Pool) run() {
for i := 0; i < p.workerNum; i++ {
go p.worker(i)
}
for task := range p.EntryChannel {
p.JobsChannel <- task
}
}
func main() {
t := NewTask(func() error {
fmt.Printf("%v", time.Now())
return nil
})
p := NewPool(4)
go func() {
for {
p.EntryChannel <- t
time.Sleep(time.Millisecond)
}
}()
p.run()
}