Skip to content

Commit 2c38c3a

Browse files
Adjusted example to handle adjusting the pool.
1 parent 15d2d84 commit 2c38c3a

2 files changed

Lines changed: 195 additions & 27 deletions

File tree

‎chapter7/patterns/work/main/main.go‎

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -29,20 +29,20 @@ type namePrinter struct {
2929
}
3030

3131
// Work implements the Worker interface.
32-
func (m *namePrinter) Work() {
32+
func (m *namePrinter) Work(id int) {
3333
fmt.Println(m.name)
3434
time.Sleep(time.Second)
3535
}
3636

3737
// main is the entry point for all Go programs.
3838
func main() {
3939
// Create a work value with 2 goroutines.
40-
w := work.New(2)
40+
w, _ := work.New(2, time.Minute)
4141

4242
var wg sync.WaitGroup
43-
wg.Add(10 * len(names))
43+
wg.Add(100 * len(names))
4444

45-
for i := 0; i < 10; i++ {
45+
for i := 0; i < 100; i++ {
4646
// Iterate over the slice of names.
4747
for _, name := range names {
4848
// Create a namePrinter and provide the
@@ -54,12 +54,24 @@ func main() {
5454
go func() {
5555
// Submit the task to be worked on. When RunTask
5656
// returns we know it is being handled.
57-
w.RunTask(&np)
57+
w.Run(&np)
5858
wg.Done()
5959
}()
6060
}
6161
}
6262

63+
for {
64+
// Enter a number and hit enter to change the size
65+
// of the work pool.
66+
var c int
67+
fmt.Scanf("%d", &c)
68+
if c == 0 {
69+
break
70+
}
71+
72+
w.Add(c)
73+
}
74+
6375
wg.Wait()
6476

6577
// Shutdown the work and wait for all existing work

‎chapter7/patterns/work/work.go‎

Lines changed: 178 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,50 +1,206 @@
11
// Copyright Information.
22

3-
// Package work manages a pool of goroutines to perform work.
4-
// Example provided with help from Jason Waldrip.
3+
// Package work manages a pool of routines to perform work.
54
package work
65

7-
import "sync"
6+
import (
7+
"errors"
8+
"fmt"
9+
"log"
10+
"sync"
11+
"sync/atomic"
12+
"time"
13+
)
14+
15+
const (
16+
addRoutine = 1
17+
rmvRoutine = 2
18+
)
19+
20+
// ErrorInvalidMinRoutines is the error for the invalid minRoutine parameter.
21+
var ErrorInvalidMinRoutines = errors.New("Invalid minimum number of routines")
22+
23+
// ErrorInvalidStatTime is the error for the invalid stat time parameter.
24+
var ErrorInvalidStatTime = errors.New("Invalid duration for stat time")
825

926
// Worker must be implemented by types that want to use
1027
// this worker processes.
1128
type Worker interface {
12-
Work()
29+
Work(id int)
1330
}
1431

15-
// Work provides a pool of goroutines that can execute any Worker
32+
// Work provides a pool of routines that can execute any Worker
1633
// tasks that are submitted.
1734
type Work struct {
18-
tasks chan Worker
19-
wg sync.WaitGroup
35+
minRoutines int // Minumum number of routines always in the pool.
36+
statTime time.Duration // Time to display stats.
37+
counter int // Maintains a running total number of routines ever created.
38+
tasks chan Worker // Unbuffered channel that work is sent into.
39+
control chan int // Unbuffered channel that work for the manager is send into.
40+
kill chan struct{} // Unbuffered channel to signal for a goroutine to die.
41+
shutdown chan struct{} // Closed when the Work pool is being shutdown.
42+
wg sync.WaitGroup // Manages the number of routines for shutdown.
43+
routines int64 // Number of routines
44+
active int64 // Active number of routines in the work pool.
45+
pending int64 // Pending number of routines waiting to submit work.
2046
}
2147

2248
// New creates a new Worker.
23-
func New(goroutines int) *Work {
49+
func New(minRoutines int, statTime time.Duration) (*Work, error) {
50+
if minRoutines <= 0 {
51+
return nil, ErrorInvalidMinRoutines
52+
}
53+
54+
if statTime < time.Millisecond {
55+
return nil, ErrorInvalidStatTime
56+
}
57+
2458
w := Work{
25-
tasks: make(chan Worker),
59+
minRoutines: minRoutines,
60+
statTime: statTime,
61+
tasks: make(chan Worker),
62+
control: make(chan int),
63+
kill: make(chan struct{}),
64+
shutdown: make(chan struct{}),
65+
}
66+
67+
// Start the manager.
68+
w.manager()
69+
70+
// Add the routines.
71+
w.Add(minRoutines)
72+
73+
return &w, nil
74+
}
75+
76+
// Add creates routines to process work or sets a count for
77+
// routines to terminate.
78+
func (w *Work) Add(routines int) {
79+
if routines == 0 {
80+
return
81+
}
82+
83+
cmd := addRoutine
84+
if routines < 0 {
85+
routines = routines * -1
86+
cmd = rmvRoutine
2687
}
2788

28-
w.wg.Add(goroutines)
29-
for i := 0; i < goroutines; i++ {
30-
go func() {
31-
for task := range w.tasks {
32-
task.Work()
89+
for i := 0; i < routines; i++ {
90+
w.control <- cmd
91+
}
92+
}
93+
94+
// work performs the users work and keeps stats.
95+
func (w *Work) work(id int) {
96+
done:
97+
for {
98+
select {
99+
case t := <-w.tasks:
100+
atomic.AddInt64(&w.active, 1)
101+
{
102+
// Perform the work.
103+
t.Work(id)
33104
}
34-
w.wg.Done()
35-
}()
105+
atomic.AddInt64(&w.active, -1)
106+
107+
case <-w.kill:
108+
break done
109+
}
36110
}
37111

38-
return &w
112+
// Decrement the counts.
113+
atomic.AddInt64(&w.routines, -1)
114+
w.wg.Done()
115+
116+
log.Println("Work : gr : Info : Shutdown")
39117
}
40118

41-
// RunTask to the worker queue
42-
func (w *Work) RunTask(task Worker) {
43-
w.tasks <- task
119+
// Run wait for the goroutine pool to take the work
120+
// to be executed.
121+
func (w *Work) Run(work Worker) {
122+
atomic.AddInt64(&w.pending, 1)
123+
{
124+
w.tasks <- work
125+
}
126+
atomic.AddInt64(&w.pending, -1)
44127
}
45128

46-
// Shutdown waits for all the workers to finish
129+
// Shutdown waits for all the workers to finish.
47130
func (w *Work) Shutdown() {
48-
close(w.tasks)
131+
close(w.shutdown)
49132
w.wg.Wait()
50133
}
134+
135+
// manager controls changes to the work pool including stats
136+
// and shutting down.
137+
func (w *Work) manager() {
138+
w.wg.Add(1)
139+
140+
go func() {
141+
log.Println("Work : manager : Started")
142+
143+
// Create a timer to run stats.
144+
timer := time.NewTimer(w.statTime)
145+
146+
for {
147+
select {
148+
case <-w.shutdown:
149+
// Capture the current number of routines.
150+
routines := int(atomic.LoadInt64(&w.routines))
151+
152+
// Send a kill to all the existing routines.
153+
for i := 0; i < routines; i++ {
154+
w.kill <- struct{}{}
155+
}
156+
157+
// Decrement the waitgroup and kill the manager.
158+
w.wg.Done()
159+
return
160+
161+
case c := <-w.control:
162+
switch c {
163+
case addRoutine:
164+
log.Println("Work : manager : Info : Add Routine")
165+
166+
// Capture a unique id.
167+
w.counter++
168+
169+
// Add to the counts.
170+
w.wg.Add(1)
171+
atomic.AddInt64(&w.routines, 1)
172+
173+
// Create the routine.
174+
go w.work(w.counter)
175+
176+
case rmvRoutine:
177+
log.Println("Work : manager : Info : Remove Routine")
178+
179+
// Capture the number of routines.
180+
routines := int(atomic.LoadInt64(&w.routines))
181+
182+
// Are there routines to remove.
183+
if routines <= w.minRoutines {
184+
log.Println("Work : manager : Info : Remove Routine Cancelled")
185+
break
186+
}
187+
188+
// Send a kill signal to remove a routine.
189+
w.kill <- struct{}{}
190+
}
191+
192+
case <-timer.C:
193+
// Capture the stats.
194+
routines := atomic.LoadInt64(&w.routines)
195+
pending := atomic.LoadInt64(&w.pending)
196+
active := atomic.LoadInt64(&w.active)
197+
198+
// Display the stats.
199+
fmt.Printf("Work : manager : Stats : G[%d] P[%d] A[%d]\n", routines, pending, active)
200+
201+
// Reset the clock.
202+
timer.Reset(w.statTime)
203+
}
204+
}
205+
}()
206+
}

0 commit comments

Comments
 (0)