1+ // http://www.golangpatterns.info/concurrency/semaphores
2+
3+ // Copyright Information.
4+ //
5+ // This sample program demonstrations how to implement a semaphore using
6+ // channels that can allow multiple reads but a single write.
7+ //
8+ // It uses the generator pattern to create channels and goroutines.
9+ //
10+ // Multiple reader/writers can be created and run concurrently. Then after
11+ // a timeout period, the program shutdowns cleanly.
12+ //
13+ // http://www.golangpatterns.info/concurrency/semaphores
14+ package main
15+
16+ import (
17+ "log"
18+ "math/rand"
19+ "sync"
20+ "sync/atomic"
21+ "time"
22+ )
23+
24+ type (
25+ // empty type represents the message the semaphore channel uses to control access.
26+ // This is a structure that requires no memory, it is truly empty.
27+ empty struct {}
28+
29+ // semaphore type represents a channel that implements the semaphore pattern.
30+ semaphore chan empty
31+ )
32+
33+ type (
34+ // readerWriter provides a structure for safely reading and writing a shared resource.
35+ // It supports multiple readers and a single writer goroutine using a semaphore construct.
36+ readerWriter struct {
37+ // The name of this object.
38+ name string
39+
40+ // write forces reading to stop to allow the write to occur safely.
41+ write sync.WaitGroup
42+
43+ // readerControl is a semaphore that allows a fixed number of reader goroutines
44+ // to read at the same time. This is our semaphore.
45+ readerControl semaphore
46+
47+ // shutdown is used to signal to running goroutines to shutdown.
48+ shutdown chan empty
49+
50+ // reportShutdown is used by the goroutines to report they are shutdown.
51+ reportShutdown sync.WaitGroup
52+
53+ // maxReads defined the maximum number of reads that can occur at a time.
54+ maxReads int
55+
56+ // maxReaders defines the number of goroutines launched to perform read operations.
57+ maxReaders int
58+
59+ // currentReads keeps a safe count of the current number of reads occurring
60+ // at any give time.
61+ currentReads int32
62+ }
63+ )
64+
65+ // init is called when the package is initialized. This code runs first.
66+ func init () {
67+ // Seed the random number generator
68+ rand .Seed (time .Now ().Unix ())
69+ }
70+
71+ // main is the entry point for the application
72+ func main () {
73+ log .Println ("Starting Process" )
74+
75+ // Create a new readerWriter with a max of 3 reads at a time
76+ // and a total of 6 reader goroutines.
77+ first := start ("First" , 3 , 6 )
78+
79+ // Create a new readerWriter with a max of 1 reads at a time
80+ // and a total of 1 reader goroutines.
81+ second := start ("Second" , 2 , 2 )
82+
83+ // Let the program run for 2 seconds.
84+ time .Sleep (2 * time .Second )
85+
86+ // Shutdown the readerWriters
87+ var waitShutdown sync.WaitGroup
88+ waitShutdown .Add (2 )
89+
90+ go first .stop (& waitShutdown )
91+ go second .stop (& waitShutdown )
92+
93+ waitShutdown .Wait ()
94+
95+ log .Println ("Process Ended" )
96+ return
97+ }
98+
99+ // start uses the generator pattern to create the readerWriter value. It launches
100+ // goroutines to process the work, returning the created ReaderWriter value.
101+ func start (name string , maxReads int , maxReaders int ) * readerWriter {
102+ // Create a value of readerWriter and initialize.
103+ rw := & readerWriter {
104+ name : name ,
105+ shutdown : make (chan empty ),
106+ maxReads : maxReads ,
107+ maxReaders : maxReaders ,
108+ readerControl : make (semaphore , maxReads ),
109+ }
110+
111+ // Launch a number of reader goroutines and let them start reading.
112+ rw .reportShutdown .Add (maxReaders )
113+ for goroutine := 0 ; goroutine < maxReaders ; goroutine ++ {
114+ go rw .reader (goroutine )
115+ }
116+
117+ // Launch the single writer goroutine and let it start writing.
118+ rw .reportShutdown .Add (1 )
119+ go rw .writer ()
120+
121+ return rw
122+ }
123+
124+ // stop signals to all goroutines to shutdown and reports back
125+ // when that is complete
126+ func (rw * readerWriter ) stop (waitShutdown * sync.WaitGroup ) {
127+ // Schedule the call to Done for once the method returns.
128+ defer waitShutdown .Done ()
129+
130+ log .Printf ("%s\t : #####> Stop" , rw .name )
131+
132+ // Close the channel which will causes all the goroutines waiting on
133+ // this channel to receive the notification to shutdown.
134+ close (rw .shutdown )
135+
136+ // Wait for all the goroutine to call Done on the waitgroup we
137+ // are waiting on.
138+ rw .reportShutdown .Wait ()
139+
140+ log .Printf ("%s\t : #####> Stopped" , rw .name )
141+ }
142+
143+ // reader is a goroutine that listens on the shutdown channel and
144+ // performs reads until the channel is signaled.
145+ func (rw * readerWriter ) reader (reader int ) {
146+ // Schedule the call to Done for once the method returns.
147+ defer rw .reportShutdown .Done ()
148+
149+ for {
150+ select {
151+ case <- rw .shutdown :
152+ log .Printf ("%s\t : #> Reader Shutdown" , rw .name )
153+ return
154+
155+ default :
156+ rw .performRead (reader )
157+ }
158+ }
159+ }
160+
161+ // performRead performs the actual reading work.
162+ func (rw * readerWriter ) performRead (reader int ) {
163+ // Get a read lock for this critical section.
164+ rw .ReadLock (reader )
165+
166+ // Safely increment the current reads counter
167+ count := atomic .AddInt32 (& rw .currentReads , 1 )
168+
169+ // Simulate some reading work
170+ log .Printf ("%s\t : [%d] Start\t - [%d] Reads\n " , rw .name , reader , count )
171+ time .Sleep (time .Duration (rand .Intn (1000 )) * time .Millisecond )
172+
173+ // Safely decrement the current reads counter
174+ count = atomic .AddInt32 (& rw .currentReads , - 1 )
175+ log .Printf ("%s\t : [%d] Finish\t - [%d] Reads\n " , rw .name , reader , count )
176+
177+ // Release the read lock for this critical section.
178+ rw .ReadUnlock (reader )
179+ }
180+
181+ // writer is a goroutine that listens on the shutdown channel and
182+ // performs writes until the channel is signaled.
183+ func (rw * readerWriter ) writer () {
184+ // Schedule the call to Done for once the method returns.
185+ defer rw .reportShutdown .Done ()
186+
187+ for {
188+ select {
189+ case <- rw .shutdown :
190+ log .Printf ("%s\t : #> Writer Shutdown" , rw .name )
191+ return
192+ default :
193+ rw .performWrite ()
194+ }
195+ }
196+ }
197+
198+ // performWrite performs the actual write work.
199+ func (rw * readerWriter ) performWrite () {
200+ // Wait a random number of milliseconds before we write again.
201+ time .Sleep (time .Duration (rand .Intn (1000 )) * time .Millisecond )
202+
203+ log .Printf ("%s\t : *****> Writing Pending\n " , rw .name )
204+
205+ // Get a write lock for this critical section.
206+ rw .WriteLock ()
207+
208+ // Simulate some writing work.
209+ log .Printf ("%s\t : *****> Writing Start" , rw .name )
210+ time .Sleep (time .Duration (rand .Intn (1000 )) * time .Millisecond )
211+ log .Printf ("%s\t : *****> Writing Finish" , rw .name )
212+
213+ // Release the write lock for this critical section.
214+ rw .WriteUnlock ()
215+ }
216+
217+ // ReadLock guarantees only the maximum number of goroutines can read at a time.
218+ func (rw * readerWriter ) ReadLock (reader int ) {
219+ // If a write is occurring, wait for it to complete.
220+ rw .write .Wait ()
221+
222+ // Acquire a buffer from the semaphore channel.
223+ rw .readerControl .Acquire (1 )
224+ }
225+
226+ // ReadUnlock gives other goroutines waiting to read their opporunity.
227+ func (rw * readerWriter ) ReadUnlock (reader int ) {
228+ // Release the buffer back into the semaphore channel.
229+ rw .readerControl .Release (1 )
230+ }
231+
232+ // WriteLock blocks all reading so the write can happen safely.
233+ func (rw * readerWriter ) WriteLock () {
234+ // Add 1 to the waitGroup so reads will block
235+ rw .write .Add (1 )
236+
237+ // Acquire all the buffers from the semaphore channel.
238+ rw .readerControl .Acquire (rw .maxReads )
239+ }
240+
241+ // WriteUnlock releases the write lock and allows reads to occur.
242+ func (rw * readerWriter ) WriteUnlock () {
243+ // Release all the buffers back into the semaphore channel.
244+ rw .readerControl .Release (rw .maxReads )
245+
246+ // Release the write lock.
247+ rw .write .Done ()
248+ }
249+
250+ // Acquire attempts to secure the specified number of buffers from the
251+ // semaphore channel.
252+ func (s semaphore ) Acquire (buffers int ) {
253+ e := empty {}
254+
255+ // Write data to secure each buffer.
256+ for buffer := 0 ; buffer < buffers ; buffer ++ {
257+ s <- e
258+ }
259+ }
260+
261+ // Release returns the specified number of buffers back into the semaphore channel.
262+ func (s semaphore ) Release (buffers int ) {
263+ // Read the data from the channel to release buffers.
264+ for buffer := 0 ; buffer < buffers ; buffer ++ {
265+ <- s
266+ }
267+ }
0 commit comments