Skip to content

Instantly share code, notes, and snippets.

@Burgestrand
Created April 3, 2013 10:43
Show Gist options
  • Save Burgestrand/5300155 to your computer and use it in GitHub Desktop.
Save Burgestrand/5300155 to your computer and use it in GitHub Desktop.
A super-simple semaphore implementation in Ruby
# coding: utf-8
require 'thread'
class Semaphore
def initialize(size = 1)
@queue = SizedQueue.new(size)
size.times { inc }
end
def inc
tap { @queue.push(nil) }
end
alias increment inc
alias up inc
def dec
tap { @queue.pop }
end
alias decrement dec
alias down dec
# @return [Integer]
def size
@queue.length
end
def synchronize
decrement
yield
ensure
increment
end
end
if $0 == __FILE__
# Example:
sem = Semaphore.new(3)
threads = Array.new(10) do |i|
Thread.start do
puts "#{i} trying to enter…"
sem.synchronize do
puts "#{i} has entered!"
sleep 5
end
sleep 0.5
puts "#{i} has left!"
end
end
threads.map(&:join)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment