Skip to content

Commit 188eff2

Browse files
New pattern for pooling goroutines to perform work
1 parent 63cda44 commit 188eff2

2 files changed

Lines changed: 107 additions & 0 deletions

File tree

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
// Copyright Information.
2+
3+
// This example is provided with help by Jason Waldrip.
4+
5+
// This sample program demostrates how to use the work package
6+
// to use a pool of goroutines to get work done.
7+
package main
8+
9+
import (
10+
"fmt"
11+
"time"
12+
13+
"github.com/goinaction/code/chapter7/patterns/work"
14+
)
15+
16+
// names provides a set of names to display.
17+
var names = []string{
18+
"steve",
19+
"bob",
20+
"mary",
21+
"therese",
22+
"jason",
23+
}
24+
25+
// namePrinter provides special support for printing names.
26+
type namePrinter struct {
27+
name string
28+
}
29+
30+
// Work implements the Worker interface.
31+
func (m *namePrinter) Work() {
32+
fmt.Println(m.name)
33+
time.Sleep(time.Second)
34+
}
35+
36+
// main is the entry point for all Go programs.
37+
func main() {
38+
// Create a work value with 2 goroutines.
39+
w := work.New(2)
40+
41+
// Iterate over the slice of names.
42+
for _, name := range names {
43+
// Create a namePrinter and provide the
44+
// specfic name.
45+
np := namePrinter{
46+
name: name,
47+
}
48+
49+
// Submit the task to be worked on. When RunTask
50+
// returns we know it is being handled.
51+
w.RunTask(&np)
52+
}
53+
54+
// Shutdown the work and wait for all existing work
55+
// to be completed.
56+
w.Shutdown()
57+
}

‎chapter7/patterns/work/work.go‎

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
// Copyright Information.
2+
3+
// Package work manages a pool of goroutines to perform work.
4+
// Example provided with help from Jason Waldrip.
5+
package work
6+
7+
import "sync"
8+
9+
// Worker must be implemented by types that want to use
10+
// this worker processes.
11+
type Worker interface {
12+
Work()
13+
}
14+
15+
// Work provides a pool of goroutines that can execute any Worker
16+
// tasks that are submitted.
17+
type Work struct {
18+
tasks chan Worker
19+
wg sync.WaitGroup
20+
}
21+
22+
// New creates a new Worker.
23+
func New(goroutines int) *Work {
24+
w := Work{
25+
tasks: make(chan Worker),
26+
}
27+
28+
w.wg.Add(goroutines)
29+
for i := 0; i < goroutines; i++ {
30+
go func() {
31+
for task := range w.tasks {
32+
task.Work()
33+
}
34+
w.wg.Done()
35+
}()
36+
}
37+
38+
return &w
39+
}
40+
41+
// RunTask to the worker queue
42+
func (w *Work) RunTask(task Worker) {
43+
w.tasks <- task
44+
}
45+
46+
// Shutdown waits for all the workers to finish
47+
func (w *Work) Shutdown() {
48+
close(w.tasks)
49+
w.wg.Wait()
50+
}

0 commit comments

Comments
 (0)