package main
import (
"fmt"
"time"
)
type Task struct {
f func() error
}
func NewTask(f func() error) *Task{
t := Task{
f: f,
}
return &t
}
func (t *Task)Run(){
t.f()
}
type pool struct {
JobsChan chan *Task
WorkerNum int
EntryChan chan *Task
}
func NewPool(workernum int) *pool{
return &pool{
make(chan *Task),
workernum,
make(chan *Task),
}
}
func(p *pool) SingleWork(id int){
for t := range p.EntryChan {
t.Run()
fmt.Println("worker i begin to work:",id)
}
}
func(p *pool)Run() {
for i:=1;i<=p.WorkerNum;i++ {
go p.SingleWork(i)
}
for task := range p.EntryChan{
p.JobsChan <- task
}
close(p.JobsChan)
close(p.EntryChan)
}
func main(){
t := NewTask(func() error {
fmt.Println(time.Now())
return nil
})
p := NewPool(3)
go func() {
for {
p.EntryChan <- t
}
}()
p.Run()
}