Skip to content

Commit d747347

Browse files
authored
Merge pull request #10 from devchat-ai/test
Enhanced GoPool with additional methods and tests
2 parents 7129fa5 + 912c593 commit d747347

File tree

2 files changed

+40
-3
lines changed

2 files changed

+40
-3
lines changed

gopool.go

Lines changed: 29 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,16 @@ import (
88

99
// GoPool represents a pool of workers.
1010
type GoPool interface {
11+
// AddTask adds a task to the pool.
1112
AddTask(t task)
13+
// Wait waits for all tasks to be dispatched and completed.
1214
Wait()
15+
// Release releases the pool and all its workers.
1316
Release()
17+
// GetRunning returns the number of running workers.
18+
Running() int
19+
// GetWorkerCount returns the number of workers.
20+
GetWorkerCount() int
1421
}
1522

1623
// task represents a function that will be executed by a worker.
@@ -49,9 +56,10 @@ func NewGoPool(maxWorkers int, opts ...Option) GoPool {
4956
pool := &goPool{
5057
maxWorkers: maxWorkers,
5158
// Set minWorkers to maxWorkers by default
52-
minWorkers: maxWorkers,
53-
workers: make([]*worker, maxWorkers),
54-
workerStack: make([]int, maxWorkers),
59+
minWorkers: maxWorkers,
60+
// workers and workerStack should be initialized after WithMinWorkers() is called
61+
workers: nil,
62+
workerStack: nil,
5563
taskQueue: make(chan task, 1e6),
5664
retryCount: 0,
5765
lock: new(sync.Mutex),
@@ -64,6 +72,10 @@ func NewGoPool(maxWorkers int, opts ...Option) GoPool {
6472
for _, opt := range opts {
6573
opt(pool)
6674
}
75+
76+
pool.workers = make([]*worker, pool.minWorkers)
77+
pool.workerStack = make([]int, pool.minWorkers)
78+
6779
if pool.cond == nil {
6880
pool.cond = sync.NewCond(pool.lock)
6981
}
@@ -187,3 +199,17 @@ func max(a, b int) int {
187199
}
188200
return b
189201
}
202+
203+
// Running returns the number of workers that are currently working.
204+
func (p *goPool) Running() int {
205+
p.lock.Lock()
206+
defer p.lock.Unlock()
207+
return len(p.workers) - len(p.workerStack)
208+
}
209+
210+
// GetWorkerCount returns the number of workers in the pool.
211+
func (p *goPool) GetWorkerCount() int {
212+
p.lock.Lock()
213+
defer p.lock.Unlock()
214+
return len(p.workers)
215+
}

gopool_test.go

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -172,3 +172,14 @@ func TestGoPoolWithTimeout(t *testing.T) {
172172
t.Errorf("Expected task to run and timeout, but it did not run")
173173
}
174174
}
175+
176+
func TestGoPoolWithMinWorkers(t *testing.T) {
177+
var minWorkers = 50
178+
179+
pool := NewGoPool(100, WithMinWorkers(minWorkers))
180+
defer pool.Release()
181+
182+
if pool.GetWorkerCount() != minWorkers {
183+
t.Errorf("Expected worker count to be %v, but got %v", minWorkers, pool.GetWorkerCount())
184+
}
185+
}

0 commit comments

Comments
 (0)