线程池实现go语言

线程池的构成:有工作者,有待上机器运作的商品,给每个工作者分配自己要负责的商品,保证他们正常运转,一件商品完成之后,要能把这个信息传递出去,然后分配下一个商品

所以结构体要有
工作者:(工作者编号)
工作的地方:工作者(work),传送带(管道chan)要处理的商品(taskQueue),保证所以商品都完成的机制(sycn.Waitgroup)

package main

import (
	"fmt"
	"sync"
)

type Worker struct {
	Id int
}

type Pool struct {
	Worker    []Worker
	TaskQueue chan func()
	wg        sync.WaitGroup
}

func main() {
	//创建线程池
	newPool := NewPool(3, 10)
	//启动工作人员
	for i := 0; i < len(newPool.Worker); i++ {
		newPool.Worker[i].Start(newPool)
	}

	//工作人员准备好,之后提交任务到线程池,让工作人员准备工作
	for i := 0; i < 8; i++ {
		id := i
		newPool.Submit(func() {
			fmt.Printf("Task %d is runing by worker %d\n", id, id%5)
		})
	}

	//关闭线程池,等待所有任务完成

	newPool.Shutdown()
}

func NewPool(worker int, taskQueue int) *Pool {
	myPool := &Pool{
		TaskQueue: make(chan func(), taskQueue),
	}
	myPool.Worker = make([]Worker, worker)
	for i := 0; i < taskQueue; i++ {
		myPool.Worker[i] = Worker{Id: i}
	}
}

func (worker Worker) Start(pool *Pool) {
	go func() {
		for task := range pool.TaskQueue {
			task()
			pool.wg.Done()
		}
	}()
}

func (pool Pool) Submit(task func()) {
	pool.wg.Add(1)
	pool.TaskQueue <- task
}

func (pool Pool) Shutdown() {
	close(pool.TaskQueue)
	pool.wg.Wait()
}
  • 8
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值