package main
import (
"fmt"
"time"
)
type task struct {
handler func() error
}
func NewTask(f func() error) task {
return task{
handler: f,
}
}
type pool struct {
EntryChan chan task
JobsChan chan task
WorkNum int8
}
func NewPool(wn int8) pool {
return pool{
EntryChan: make(chan task, 100),
JobsChan: make(chan task, 100),
WorkNum: wn,
}
}
func (p pool) Worker(wid int) {
for task := range p.JobsChan {
task.handler()
fmt.Printf("WorkId: %d 執行完成\n", wid)
}
}
func (p pool) Run() {
for task := range p.EntryChan {
p.JobsChan <- task
}
}
func main() {
task := NewTask(func() error {
fmt.Println("執行任務中...", time.Now().Format("2006-01-02 15:04:05"))
return nil
})
p := NewPool(4)
for i := 0; i < int(p.WorkNum); i++ {
go p.Worker(i)
}
go func() {
for {
p.EntryChan <- task
time.Sleep(1 * time.Second)
}
}()
p.Run()
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結