实现简单的线程池,任务放在entry中,线程池开启后会创建相应数目的线程,不断从entry中拿取任务放在work管道中,并且不断从work中取出任务运行
package main
import "fmt"
var count int
type Task struct {
myfun func()error
}
func NewTask(fun func()error)*Task {
return &Task{
myfun: fun,
}
}
func (m*Task)Excute() {
m.myfun()
}
type GroutinePool struct {
Sum int
EntryTask chan *Task
WorkTask chan *Task
}
func NewGroutinePool(sum int)*GroutinePool {
return &GroutinePool{
Sum: sum,
EntryTask: make(chan *Task),
WorkTask: make(chan *Task),
}
}
func (pool*GroutinePool)Work(workid int) {
for task:=range pool.WorkTask{
task.Excute()
count++
fmt.Println("第几个线程执行完成",workid,"执行次数",count)
}
}
func (pool*GroutinePool)Run() {
for i:=0;i<pool.Sum;i++{
go func() {
pool.Work(i)
}()
}
for task:=range pool.EntryTask{
pool.WorkTask<-task
}
}
func testwork() error {
fmt.Println("这是一个测试任务")
return nil
}
func main() {
p:=NewGroutinePool(40)
go func() {
for {
p.EntryTask<-NewTask(testwork)
}
}()
p.Run()
}