package main
import (
"fmt"
"time"
)
type Pool struct {
work chan func() // 任务
size chan struct{} // 数量
}
func New(size int) *Pool {
return &Pool{
work: make(chan func()),
size: make(chan struct{}, size),
}
}
func (p *Pool) worker(task func()) {
fmt.Println(111)
defer func() { <-p.size }()
for {
task()
<-p.work
}
fmt.Println(222)
}
func (p *Pool) NewTask(task func()) {
select {
case p.work <- task:
fmt.Println(333)
case p.size <- struct{}{}:
fmt.Println(444)
go p.worker(task)
}
}
func main() {
pool := New(2)
for i := 1; i < 5; i++ {
pool.NewTask(func() {
time.Sleep(2 * time.Second)
fmt.Println(time.Now())
})
}
// 保证所有的协程都执行完毕
time.Sleep(10 * time.Second)
}