11require 'concurrent/synchronization'
22
33module Concurrent
4+
5+ # @!macro [attach] semaphore
6+ #
7+ # A counting semaphore. Conceptually, a semaphore maintains a set of
8+ # permits. Each {#acquire} blocks if necessary until a permit is
9+ # available, and then takes it. Each {#release} adds a permit, potentially
10+ # releasing a blocking acquirer.
11+ # However, no actual permit objects are used; the Semaphore just keeps a
12+ # count of the number available and acts accordingly.
413 class MutexSemaphore < Synchronization ::Object
14+
515 # @!macro [attach] semaphore_method_initialize
616 #
717 # Create a new `Semaphore` with the initial `count`.
@@ -129,12 +139,14 @@ def reduce_permits(reduction)
129139
130140 protected
131141
142+ # @!visibility private
132143 def ns_initialize ( count )
133144 @free = count
134145 end
135146
136147 private
137148
149+ # @!visibility private
138150 def try_acquire_now ( permits )
139151 if @free >= permits
140152 @free -= permits
@@ -144,28 +156,45 @@ def try_acquire_now(permits)
144156 end
145157 end
146158
159+ # @!visibility private
147160 def try_acquire_timed ( permits , timeout )
148161 ns_wait_until ( timeout ) { try_acquire_now ( permits ) }
149162 end
150163 end
151164
152- if Concurrent . on_jruby?
165+ SemaphoreImplementation = case
166+ when Concurrent . on_jruby?
167+ JavaSemaphore
168+ else
169+ MutexSemaphore
170+ end
171+ private_constant :SemaphoreImplementation
153172
154- # @!macro semaphore
155- #
156- # A counting semaphore. Conceptually, a semaphore maintains a set of
157- # permits. Each {#acquire} blocks if necessary until a permit is
158- # available, and then takes it. Each {#release} adds a permit, potentially
159- # releasing a blocking acquirer.
160- # However, no actual permit objects are used; the Semaphore just keeps a
161- # count of the number available and acts accordingly.
162- class Semaphore < JavaSemaphore
163- end
173+ # @!macro semaphore
174+ #
175+ # @see Concurrent::MutexSemaphore
176+ class Semaphore < SemaphoreImplementation
164177
165- else
178+ # @!method initialize(count)
179+ # @!macro semaphore_method_initialize
180+
181+ # @!method acquire(permits = 1)
182+ # @!macro semaphore_method_acquire
183+
184+ # @!method available_permits
185+ # @!macro semaphore_method_available_permits
186+
187+ # @!method drain_permits
188+ # @!macro semaphore_method_drain_permits
189+
190+ # @!method try_acquire(permits = 1, timeout = nil)
191+ # @!macro semaphore_method_try_acquire
192+
193+ # @!method release(permits = 1)
194+ # @!macro semaphore_method_release
195+
196+ # @!method reduce_permits(reduction)
197+ # @!macro semaphore_method_reduce_permits
166198
167- # @!macro semaphore
168- class Semaphore < MutexSemaphore
169- end
170199 end
171200end
0 commit comments