Prompts for GPT
User
gopool.go
package gopooltype Task func()
type GoPool struct { TaskQueue chan Task MaxWorkers int Workers []*Worker }
func NewGoPool(maxWorkers int) *GoPool { pool := &GoPool{ TaskQueue: make(chan Task), MaxWorkers: maxWorkers, Workers: make([]*Worker, maxWorkers), } for i := 0; i < maxWorkers; i++ { worker := newWorker(pool.TaskQueue) pool.Workers[i] = worker worker.start() } return pool }
func (p *GoPool) AddTask(task Task) { p.TaskQueue <- task }
func (p *GoPool) Release() { close(p.TaskQueue) for _, worker := range p.Workers { <-worker.TaskQueue } }
worker.go
package gopooltype Worker struct { TaskQueue chan Task }
func newWorker(taskQueue chan Task) *Worker { return &Worker{ TaskQueue: taskQueue, } }
func (w *Worker) start() { go func() { for task := range w.TaskQueue { if task != nil { task() } } }() }
Now I need you to:
- Add UT to gopool_test.go;
- Add performance test code to see how long it takes to process one million simple tasks with a Pool capacity of 10000;
- Add performance test code for scenarios without using GoPool to see how long it takes to process one million simple tasks directly using go to open goroutines.
DevChat
Here is the unit test and performance test code I added for GoPool
:
In the gopool_test.go
file:
package gopool
import (
"testing"
"time"
)
func TestGoPool(t *testing.T) {
pool := NewGoPool(100)
for i := 0; i < 1000; i++ {
pool.AddTask(func() {
time.Sleep(10 * time.Millisecond)
})
}
pool.Release()
}
func BenchmarkGoPool(b *testing.B) {
pool := NewGoPool(10000)
b.ResetTimer()
for i := 0; i < b.N; i++ {
pool.AddTask(func() {
time.Sleep(10 * time.Millisecond)
})
}
pool.Release()
}
func BenchmarkGoroutines(b *testing.B) {
tasks := make(chan Task, b.N)
for i := 0; i < b.N; i++ {
tasks <- func() {
time.Sleep(10 * time.Millisecond)
}
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
go (<-tasks)()
}
close(tasks)
}
In this test, TestGoPool
tests the basic functionality of GoPool
, i.e., adding tasks and releasing the Pool. BenchmarkGoPool
and BenchmarkGoroutines
test the performance of using GoPool
and directly using goroutines to handle one million simple tasks, respectively.
Please note that the tasks in these tests are simple functions that just sleep for a while. In actual applications, tasks may be more complex, so these test results may not fully reflect the performance of GoPool
in actual applications.