Skip to content

Commit 2464f24

Browse files
Refactored code to highlight the stream processing.
1 parent 7341164 commit 2464f24

1 file changed

Lines changed: 121 additions & 81 deletions

File tree

‎chapter6/patterns/stream/stream.go‎

Lines changed: 121 additions & 81 deletions
Original file line numberDiff line numberDiff line change
@@ -7,117 +7,163 @@ package main
77
import (
88
"log"
99
"sync"
10+
"time"
1011

1112
"github.com/goinaction/code/chapter6/patterns/stream/station"
1213
"github.com/goinaction/code/chapter6/patterns/stream/timezone"
1314
)
1415

1516
const (
16-
buffer = 30
17-
totalWorkers = 10
1817
geoNamesUserName = "ardanstudios"
1918
)
2019

21-
func main() {
22-
FindTimezones()
23-
}
20+
// processor manages a stream of work.
21+
type processor struct {
22+
// This channel is used to shutdown the program.
23+
shutdown chan struct{}
24+
25+
// The WaitGroup keeps track of all running goroutines.
26+
waitGroup sync.WaitGroup
2427

25-
// FindTimezones use concurrency to retrieve timezones for a set of stations.
26-
func FindTimezones() {
2728
// This channel buffers all the work coming in off the stream.
28-
stream := make(chan *station.Station, buffer)
29+
stream chan *station.Station
2930

3031
// This channel contains the current work being processed.
31-
work := make(chan *station.Station, totalWorkers)
32+
work chan *station.Station
3233

3334
// This channel is used to communicate work that has been processed
3435
// back to the main processing routine.
35-
processed := make(chan *station.Station, 1)
36-
37-
totalStations := StartStream(stream)
38-
LaunchWorkRoutines(work, processed)
39-
stations := ProcessWork(stream, work, processed, totalStations)
36+
processed chan *station.Station
4037

41-
// Shutdown the goroutines that perform the work
42-
close(work)
38+
// Total number of workers to process work.
39+
totalWorkers int
40+
}
4341

44-
// Display the results for all the processed work.
45-
for _, station := range stations {
46-
if station.Err != nil {
47-
log.Printf("Station[%s]\tERROR[%s]\n", station.Name, station.Err)
48-
} else {
49-
log.Printf("Station[%s]\tTZ[%s]\n", station.Name, station.Timezone.TimezoneId)
50-
}
42+
// FindTimezones use concurrency to retrieve timezones for a set of stations.
43+
func main() {
44+
p := processor{
45+
shutdown: make(chan struct{}),
46+
stream: make(chan *station.Station, 30),
47+
work: make(chan *station.Station, 10),
48+
processed: make(chan *station.Station, 1),
49+
totalWorkers: 10,
5150
}
51+
52+
p.Run()
53+
time.Sleep(5 * time.Second)
54+
p.Shutdown()
55+
}
56+
57+
// Run launches the goroutines to process the stream.
58+
func (p *processor) Run() {
59+
p.LaunchWorkRoutines()
60+
p.ProcessWork()
61+
p.StartStream()
62+
}
63+
64+
// Shutdown shutdown all the running goroutines.
65+
func (p *processor) Shutdown() {
66+
log.Println("Shutdown\t: Started")
67+
68+
close(p.shutdown)
69+
p.waitGroup.Wait()
70+
71+
log.Println("Shutdown\t: Completed")
5272
}
5373

5474
// StartStream simulates the loading of work from a stream into the stream channel so
5575
// it can be processed.
56-
func StartStream(stream chan<- *station.Station) int {
57-
// Retrieve the set of stations to process.
58-
stations := station.LoadStations()
76+
func (p *processor) StartStream() {
77+
p.waitGroup.Add(1)
5978

6079
// Launch a goroutine to load these stations
6180
// into the stream channel.
6281
go func() {
63-
for _, station := range stations {
64-
stream <- station
65-
}
82+
for {
83+
log.Println("Stream\t: Send Burst")
6684

67-
// Close the stream channel once the last station
68-
// is loaded. This will let us determine when the last
69-
// station is pulled from the stream.
70-
close(stream)
71-
}()
85+
// Read the file for work to be accomplished.
86+
stations := station.LoadStations()
87+
88+
// Load the work into the stream channel.
89+
for _, station := range stations {
90+
p.stream <- station
91+
}
7292

73-
// Return the number of stations we will be processing.
74-
return len(stations)
93+
select {
94+
// If we are being signaled to shutdown, do so.
95+
case <-p.shutdown:
96+
log.Println("Stream\t: Shutdown")
97+
p.waitGroup.Done()
98+
return
99+
100+
// Sleep for two seconds and send another burst.
101+
case <-time.After(2 * time.Second):
102+
}
103+
}
104+
}()
75105
}
76106

77107
// LaunchWorkRoutines launch the goroutines that perform the actual work. These goroutines
78108
// call into the GeoNames api to retrieve the timezone information for each station.
79-
func LaunchWorkRoutines(work <-chan *station.Station, processed chan<- *station.Station) {
80-
for worker := 0; worker <= totalWorkers; worker++ {
109+
func (p *processor) LaunchWorkRoutines() {
110+
p.waitGroup.Add(p.totalWorkers)
111+
112+
for worker := 0; worker <= p.totalWorkers; worker++ {
81113
// Launch a goroutine to process work.
82114
go func() {
83-
// Pull a station off the work channel.
84-
for station := range work {
85-
log.Printf("Work\t: Processing\t: %s\n", station.Name)
86-
87-
// Call into the geonames api.
88-
station.Timezone, station.Err = timezone.RetrieveGeoNamesTimezone(
89-
station.Location.Coordinates[1],
90-
station.Location.Coordinates[0],
91-
geoNamesUserName)
92-
93-
// Push the station on the processed channel
94-
// so it can be saved and returned.
95-
processed <- station
115+
for {
116+
select {
117+
case <-p.shutdown:
118+
log.Println("Work\t: Shutdown")
119+
p.waitGroup.Done()
120+
return
121+
122+
// Pull a station off the work channel.
123+
case station := <-p.work:
124+
log.Printf("Work\t: Processing\t: %s\n", station.Name)
125+
126+
// Call into the geonames api.
127+
station.Timezone, station.Err = timezone.RetrieveGeoNamesTimezone(
128+
station.Location.Coordinates[1],
129+
station.Location.Coordinates[0],
130+
geoNamesUserName)
131+
132+
select {
133+
case <-p.shutdown:
134+
log.Println("Work\t: Shutdown")
135+
p.waitGroup.Done()
136+
return
137+
138+
default:
139+
}
140+
141+
// Push the station on the processed channel
142+
// so it can be saved and returned.
143+
p.processed <- station
144+
}
96145
}
97-
98-
log.Println("Work\t: Shutdown")
99146
}()
100147
}
101148
}
102149

103150
// ProcessWork coordinates the work of retrieving timezone information for all the work in the stream. It move
104151
// work from the stream into the work channel and receives processed worked.
105-
func ProcessWork(stream <-chan *station.Station, work chan<- *station.Station, processed <-chan *station.Station, totalStations int) []*station.Station {
106-
// Create a waitgroup to wait for all the stations to be processed.
107-
var waitGroup sync.WaitGroup
108-
waitGroup.Add(totalStations)
109-
110-
// Slice of processes stations to be returned.
111-
stations := make([]*station.Station, totalStations)
152+
func (p *processor) ProcessWork() {
153+
p.waitGroup.Add(1)
112154

113155
go func() {
114-
streamBuffer := stream // Using a temp vartiable to control the flow of the stream.
115-
streamClosed := false // Flag to determine when the stream is closed.
116-
busyWorkers := 0 // Tracks the number of worker routines that are busy.
117-
completed := 0 // Tracks the number of stations completed.
156+
streamBuffer := p.stream // Using a temp vartiable to control the flow of the stream.
157+
streamClosed := false // Flag to determine when the stream is closed.
158+
busyWorkers := 0 // Tracks the number of worker routines that are busy.
118159

119160
for {
120161
select {
162+
case <-p.shutdown:
163+
log.Println("Processor\t: Shutdown")
164+
p.waitGroup.Done()
165+
return
166+
121167
// Pull work off the stream.
122168
case station, ok := <-streamBuffer:
123169
if !ok {
@@ -131,44 +177,38 @@ func ProcessWork(stream <-chan *station.Station, work chan<- *station.Station, p
131177
log.Printf("Stream\t: Posting\t: Name[%s] Count[%d]\n", station.Name, busyWorkers)
132178

133179
// Send the station to the work channel for processing.
134-
work <- station
180+
p.work <- station
135181

136182
// If all the work goroutines are busy, don't process any
137183
// more stations from the stream. Let's get some work done.
138-
if busyWorkers == totalWorkers {
184+
if busyWorkers == p.totalWorkers {
139185
log.Printf("Stream\t: Paused\t: Count[%d]\n", busyWorkers)
140186
streamBuffer = nil
141187
}
142188

143189
// Work that has been processed.
144-
case station := <-processed:
190+
case station := <-p.processed:
191+
if station == nil {
192+
log.Println("Process\t: Shutdown")
193+
p.waitGroup.Done()
194+
return
195+
}
196+
145197
busyWorkers--
146198
if station.Err != nil {
147199
log.Printf("Work\t: ERROR\t: Name[%s] ERROR[%s] Count[%d]\n", station.Name, station.Err, busyWorkers)
148200
} else {
149201
log.Printf("Work\t: Completed\t: Name[%s] TZ[%s] Count[%d]\n", station.Name, station.Timezone.TimezoneId, busyWorkers)
150202
}
151203

152-
// Store the station in the final slice.
153-
stations[completed] = station
154-
completed++
155-
156-
// Report that work for this station is complete.
157-
waitGroup.Done()
158-
159204
// Neither the stream nor the processed channel has work to do. Determine
160205
// if we open the stream again.
161206
default:
162-
if streamBuffer == nil && (busyWorkers < totalWorkers) && !streamClosed {
207+
if streamBuffer == nil && (busyWorkers < p.totalWorkers) && !streamClosed {
163208
log.Printf("Stream\t: Opened\t: Count[%d]\n", busyWorkers)
164-
streamBuffer = stream
209+
streamBuffer = p.stream
165210
}
166211
}
167212
}
168213
}()
169-
170-
// Wait until all the stations have been processed.
171-
waitGroup.Wait()
172-
173-
return stations
174214
}

0 commit comments

Comments
 (0)