Skip to content

Commit fefd82f

Browse files
Refactored shutdown code.
1 parent fae32ee commit fefd82f

1 file changed

Lines changed: 17 additions & 8 deletions

File tree

‎chapter6/patterns/semaphore/semaphore.go‎

Lines changed: 17 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -81,14 +81,8 @@ func main() {
8181
// Let the program run for 2 seconds.
8282
time.Sleep(2 * time.Second)
8383

84-
// Shutdown the readerWriters
85-
var waitShutdown sync.WaitGroup
86-
waitShutdown.Add(2)
87-
88-
go first.stop(&waitShutdown)
89-
go second.stop(&waitShutdown)
90-
91-
waitShutdown.Wait()
84+
// Shutdown both of the readerWriter processes.
85+
shutdown(first, second)
9286

9387
log.Println("Process Ended")
9488
return
@@ -119,6 +113,21 @@ func start(name string, maxReads int, maxReaders int) *readerWriter {
119113
return &rw
120114
}
121115

116+
// shutdown stops all of the existing readerWriter processes concurrently.
117+
func shutdown(readerWriters ...*readerWriter) {
118+
// Create a WaitGroup to track the shutdowns.
119+
var waitShutdown sync.WaitGroup
120+
waitShutdown.Add(2)
121+
122+
// Launch each call to the stop method as a goroutine.
123+
for _, readerWriter := range readerWriters {
124+
go readerWriter.stop(&waitShutdown)
125+
}
126+
127+
// Wait for all the goroutines to report they are done.
128+
waitShutdown.Wait()
129+
}
130+
122131
// stop signals to all goroutines to shutdown and reports back
123132
// when that is complete
124133
func (rw *readerWriter) stop(waitShutdown *sync.WaitGroup) {

0 commit comments

Comments
 (0)