go协程池

package main

import (
"fmt"
"time"
)
func main() {
cap_num := 5

pool := NewPool(cap_num)
go func() {
for {
task := NewTask(func() {
fmt.Println(time.Now())
})
pool.InChannel <- task
}
}()
//任务调度
pool.PoolRun()
}
type Task struct {
F func()
}
//创建任务
func NewTask(f func()) *Task {
task := Task{F:f}
return &task
}
//任务执行
func (t *Task) TaskRun() {
t.F()
}
//协程池
type GoroutinePool struct {
CapNum int
//进任务的管道
InChannel chan *Task
//任务调度的管道
WorkChannel chan *Task
}
func NewPool(cap_num int) *GoroutinePool {
pool := GoroutinePool{
CapNum:cap_num,
InChannel:make(chan *Task),
WorkChannel: make(chan *Task),
}
return &pool
}
//从Inchannel管道拿到任务,放到WorkChannel
func (p *GoroutinePool) TaskInChannelOut() {
for task := range p.InChannel {
p.WorkChannel <- task
}
}
//任务执行者从WorkChannel 获取任务并执行
func (p *GoroutinePool) Worker() {
for task := range p.WorkChannel {
task.TaskRun()
fmt.Println("任务书执行完毕")
}
}
func (p *GoroutinePool) PoolRun() {
//任务执行
for i := 0; i < p.CapNum; i++ {
go p.Worker() //开启指定数量的协程执行任务
}
//从InChannel管道拿到任务
p.TaskInChannelOut()
close(p.WorkChannel)
close(p.InChannel)
}
posted @ 2021-02-11 10:03  zhangsima  阅读(199)  评论(0编辑  收藏  举报