go工作池模板记录
发布人:shili8
发布时间:2025-01-10 16:24
阅读次数:0
**Go 工作池模板**
### 概述本文提供了一个基本的 Go 工作池模板,用于管理并发任务。该模板使用 Goroutine 和 Channel 来实现高效的任务处理。
###依赖* Go1.17 或更高版本* `sync` 包(内置)
* `container/list` 包(内置)
### 工作池结构
go// WorkerPool.gopackage mainimport (
"sync"
)
// WorkerPool represents a worker pool with a fixed number of workers.
type WorkerPool struct {
workers int queue *list.List mu sync.Mutex workChan chan func()
}
// NewWorkerPool returns a new worker pool with the specified number of workers.
func NewWorkerPool(workers int) *WorkerPool {
return &WorkerPool{
workers: workers,
queue: list.New(),
workChan: make(chan func(), workers),
}
}
### 工作池方法
go// Start starts the worker pool, executing tasks from the queue.
func (p *WorkerPool) Start() {
for i :=0; i < p.workers; i++ {
go p.worker()
}
p.startWorkers()
}
// Stop stops all workers in the pool.
func (p *WorkerPool) Stop() {
close(p.workChan)
p.mu.Lock()
defer p.mu.Unlock()
for worker := range p.queue.Back().Value.(chan func()) {
close(worker)
}
}
// AddTask adds a new task to the queue.
func (p *WorkerPool) AddTask(task func()) {
p.mu.Lock()
defer p.mu.Unlock()
if p.queue.Len() >= cap(p.workChan) {
return}
p.queue.PushBack(make(chan func()))
p.queue.Value.(chan func()).<-task select {
case <-p.workChan:
default:
}
}
// worker is a single worker function that executes tasks from the queue.
func (p *WorkerPool) worker() {
for task := range p.workChan {
task()
}
}
### 使用示例
gopackage mainimport (
"fmt"
"time"
"github.com/your/project/WorkerPool"
)
func main() {
p := WorkerPool.NewWorkerPool(5)
defer p.Stop()
go p.Start()
for i :=0; i < 10; i++ {
time.Sleep(time.Second)
fmt.Printf("Adding task %d
", i)
p.AddTask(func() { fmt.Println("Task executed") })
}
}
### 总结本文提供了一个基本的 Go 工作池模板,用于管理并发任务。该模板使用 Goroutine 和 Channel 来实现高效的任务处理。您可以根据具体需求进行扩展和修改。
**注意**
* 本示例代码仅供参考,并不保证在所有环境下都能正常工作。
* 您应该仔细检查和测试您的代码,以确保其正确性和安全性。
* 如果您发现任何错误或有改进的建议,请随时联系我。

