Created
June 20, 2012 18:21
-
-
Save seanlilmateus/2961387 to your computer and use it in GitHub Desktop.
Macruby and Rubymotion GCD Semaphore example (sleeping barber problem)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env macruby -wKU | |
# A GCD-based implementation of the sleeping barber problem: | |
# http://en.wikipedia.org/wiki/Sleeping_barber_problem | |
# http://www.madebysofa.com/#blog/the_sleeping_barber | |
waiting_chairs = Dispatch::Queue.new('com.apple.waiting_chairs') | |
semaphore = Dispatch::Semaphore.new(3) | |
index = -1 | |
while true | |
index += 1 | |
success = semaphore.wait(Dispatch::TIME_NOW) | |
if success != 0 | |
puts "Customer turned away #{index}" | |
next | |
end | |
waiting_chairs.async do | |
semaphore.signal | |
puts "Shave and a haircut #{index}" | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment