Skip to content

Commit f2b7098

Browse files
Updating code for chapter.
1 parent f9ecc46 commit f2b7098

8 files changed

Lines changed: 33 additions & 215 deletions

File tree

‎chapter7/patterns/pool/main/main.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
// Copyright Information.
22

3-
// This example is provided with help by Gabriel Aszalos.
3+
// Example is provided with help by Gabriel Aszalos.
44

55
// This sample program demonstrates how to use the pool package
66
// to share a simulated set of database connections.

‎chapter7/patterns/pool/pool.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
// Copyright Information.
22

3-
// Package pool manages a user defined set of resources.
43
// Example provided with help from Fatih Arslan and Gabriel Aszalos.
4+
// Package pool manages a user defined set of resources.
55
package pool
66

77
import (

‎chapter7/patterns/runner/main/main.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
// Copyright Information.
22

3-
// This example is provided with help by Gabriel Aszalos.
3+
// Example is provided with help by Gabriel Aszalos.
44

55
// This sample program demonstrates how to use a channel to
66
// monitor the amount of time the program is running and terminate

‎chapter7/patterns/runner/runner.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
// Copyright Information.
22

3+
// Example is provided with help by Gabriel Aszalos.
34
// Package runner manages the running and lifetime of a process.
4-
// Example provided with help from Gabriel Aszalos.
55
package runner
66

77
import (

‎chapter7/patterns/search/main/main.go‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
// Copyright Information.
22

3+
// Example provided with help from Gabriel Aszalos.
4+
35
// This sample program demonstrates how to implement a pattern for
46
// concurrent requesting results from different systems and either
57
// wait for all the results to return or just the first one.

‎chapter7/patterns/search/search.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
// Copyright Information.
22

3+
// Example provided with help from Gabriel Aszalos.
34
// Package search : search.go manages the searching of results
45
// against Google, Yahoo and Bing.
5-
// Example provided with help from Gabriel Aszalos.
66
package search
77

88
import "log"

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

Lines changed: 4 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,13 @@
11
// Copyright Information.
22

3-
// This example is provided with help by Jason Waldrip.
3+
// Example is provided with help by Jason Waldrip.
44

55
// This sample program demostrates how to use the work package
66
// to use a pool of goroutines to get work done.
77
package main
88

99
import (
1010
"fmt"
11-
"log"
1211
"sync"
1312
"time"
1413

@@ -30,21 +29,15 @@ type namePrinter struct {
3029
}
3130

3231
// Work implements the Worker interface.
33-
func (m *namePrinter) Work(id int) {
32+
func (m *namePrinter) Work() {
3433
fmt.Println(m.name)
3534
time.Sleep(time.Second)
3635
}
3736

38-
// logger is called by the work pool when
39-
// it has things to log.
40-
func logger(message string) {
41-
log.Println(message)
42-
}
43-
4437
// main is the entry point for all Go programs.
4538
func main() {
4639
// Create a work value with 2 goroutines.
47-
w, _ := work.New(2, time.Second, logger)
40+
w := work.New(2)
4841

4942
var wg sync.WaitGroup
5043
wg.Add(100 * len(names))
@@ -61,24 +54,12 @@ func main() {
6154
go func() {
6255
// Submit the task to be worked on. When RunTask
6356
// returns we know it is being handled.
64-
w.Run(&np)
57+
w.RunTask(&np)
6558
wg.Done()
6659
}()
6760
}
6861
}
6962

70-
for {
71-
// Enter a number and hit enter to change the size
72-
// of the work pool.
73-
var c int
74-
fmt.Scanf("%d", &c)
75-
if c == 0 {
76-
break
77-
}
78-
79-
w.Add(c)
80-
}
81-
8263
wg.Wait()
8364

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

‎chapter7/patterns/work/work.go‎

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

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

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

259
// Worker must be implemented by types that want to use
2610
// this worker processes.
2711
type Worker interface {
28-
Work(id int)
12+
Work()
2913
}
3014

31-
// Work provides a pool of routines that can execute any Worker
15+
// Work provides a pool of goroutines that can execute any Worker
3216
// tasks that are submitted.
3317
type Work struct {
34-
minRoutines int // Minumum number of routines always in the pool.
35-
statTime time.Duration // Time to display stats.
36-
counter int // Maintains a running total number of routines ever created.
37-
tasks chan Worker // Unbuffered channel that work is sent into.
38-
control chan int // Unbuffered channel that work for the manager is send into.
39-
kill chan struct{} // Unbuffered channel to signal for a goroutine to die.
40-
shutdown chan struct{} // Closed when the Work pool is being shutdown.
41-
wg sync.WaitGroup // Manages the number of routines for shutdown.
42-
routines int64 // Number of routines
43-
active int64 // Active number of routines in the work pool.
44-
pending int64 // Pending number of routines waiting to submit work.
45-
46-
logFunc func(message string) // Function called to providing logging support
18+
tasks chan Worker
19+
wg sync.WaitGroup
4720
}
4821

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

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

114-
// Decrement the counts.
115-
atomic.AddInt64(&w.routines, -1)
116-
w.wg.Done()
117-
118-
w.log("Worker : Shutting Down")
38+
return &w
11939
}
12040

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

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

0 commit comments

Comments
 (0)