-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathworker_pool.go
More file actions
42 lines (36 loc) · 978 Bytes
/
worker_pool.go
File metadata and controls
42 lines (36 loc) · 978 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package cron
import (
"runtime"
"sync"
)
// WorkerPool manages concurrent job execution
type WorkerPool struct {
semaphore chan struct{}
wg sync.WaitGroup
}
// NewWorkerPool creates a worker pool with specified max workers.
// If maxWorkers <= 0, a default cap of runtime.NumCPU() * 128 is used.
func NewWorkerPool(maxWorkers int) *WorkerPool {
if maxWorkers <= 0 {
maxWorkers = runtime.NumCPU() * 128
}
return &WorkerPool{
semaphore: make(chan struct{}, maxWorkers),
}
}
// Submit submits a job to the worker pool.
// The semaphore acquisition happens inside the goroutine so that the caller
// (the scheduler's run() loop) is never blocked by a saturated pool.
func (wp *WorkerPool) Submit(job func()) {
wp.wg.Add(1)
go func() {
wp.semaphore <- struct{}{} // acquire slot inside goroutine
defer wp.wg.Done()
defer func() { <-wp.semaphore }()
job()
}()
}
// Wait waits for all jobs to complete
func (wp *WorkerPool) Wait() {
wp.wg.Wait()
}