Skip to content

Instantly share code, notes, and snippets.

@seanlilmateus
Created June 20, 2012 18:21
Show Gist options
  • Save seanlilmateus/2961387 to your computer and use it in GitHub Desktop.
Save seanlilmateus/2961387 to your computer and use it in GitHub Desktop.
Macruby and Rubymotion GCD Semaphore example (sleeping barber problem)
#!/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