Skip to content

Commit f95b83c

Browse files
committed
Add Semaphore documentation example
1 parent 09cd1d2 commit f95b83c

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

futures.rb

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
require 'concurrent'
2+
3+
Array.new(4) do
4+
Concurrent.zip(
5+
Array.new(5) do |i|
6+
Concurrent::Delay.new do
7+
puts "starting #{i}"
8+
sleep(i)
9+
puts "done #{i}"
10+
i
11+
end
12+
end
13+
)
14+
end.inject { |a,b| a.chain { b }.flat }.value!

lib/concurrent/atomic/semaphore.rb

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,38 @@ module Concurrent
108108
# count of the number available and acts accordingly.
109109
#
110110
# @!macro semaphore_public_api
111+
# @example
112+
# semaphore = Concurrent::Semaphore.new(2)
113+
#
114+
# t1 = Thread.new do
115+
# semaphore.acquire
116+
# puts "Thread 1 acquired semaphore"
117+
# end
118+
#
119+
# t2 = Thread.new do
120+
# semaphore.acquire
121+
# puts "Thread 2 acquired semaphore"
122+
# end
123+
#
124+
# t3 = Thread.new do
125+
# semaphore.acquire
126+
# puts "Thread 3 acquired semaphore"
127+
# end
128+
#
129+
# t4 = Thread.new do
130+
# sleep(2)
131+
# puts "Thread 4 releasing semaphore"
132+
# semaphore.release
133+
# end
134+
#
135+
# [t1, t2, t3, t4].each(&:join)
136+
#
137+
# outputs
138+
# "Thread 3 acquired semaphore"
139+
# "Thread 2 acquired semaphore"
140+
# "Thread 4 releasing semaphore"
141+
# "Thread 1 acquired semaphore"
142+
#
111143
class Semaphore < SemaphoreImplementation
112144
end
113145
end

0 commit comments

Comments
 (0)