-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpool.go
More file actions
68 lines (58 loc) · 1.7 KB
/
Copy pathpool.go
File metadata and controls
68 lines (58 loc) · 1.7 KB
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package workerpool
import (
"fmt"
"sync"
"time"
)
// Job represents a proxy work item, e.g., logging a request asynchronously.
type Job struct {
ID int
Query string
}
// Dispatcher starts the worker pool and handles job submission smoothly.
type Dispatcher struct {
JobQueue chan Job
numWorkers int
wg sync.WaitGroup
}
func NewDispatcher(numWorkers int, bufferSize int) *Dispatcher {
return &Dispatcher{
JobQueue: make(chan Job, bufferSize),
numWorkers: numWorkers,
}
}
// Start boots up the worker goroutines. This is a common pattern to avoid spawning
// infinite goroutines which can lead to Out-Of-Memory errors on servers under load.
func (d *Dispatcher) Start() {
fmt.Printf("Starting %d workers...\n", d.numWorkers)
for i := 1; i <= d.numWorkers; i++ {
d.wg.Add(1)
go d.worker(i)
}
}
// worker constantly pulls from the JobQueue until the channel is closed.
func (d *Dispatcher) worker(id int) {
defer d.wg.Done()
for job := range d.JobQueue {
// Simulate proxy workload
fmt.Printf("Worker %d processing Job %d: %s\n", id, job.ID, job.Query)
time.Sleep(10 * time.Millisecond) // Compute bound task
}
fmt.Printf("Worker %d shutting down.\n", id)
}
// Wait blocks until all jobs are done AND the pool gracefully shuts down.
func (d *Dispatcher) Wait() {
close(d.JobQueue) // Signals to workers that no more jobs are coming
d.wg.Wait()
}
// RunWorkerPoolExample demonstrates the pattern.
func RunWorkerPoolExample() {
dispatcher := NewDispatcher(3, 100)
dispatcher.Start()
// Submit 10 async jobs
for i := 1; i <= 10; i++ {
dispatcher.JobQueue <- Job{ID: i, Query: fmt.Sprintf("SQL query %d", i)}
}
dispatcher.Wait()
fmt.Println("Worker pool drained and closed.")
}