Skip to content

Instantly share code, notes, and snippets.

@rklemme
Created February 16, 2010 21:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rklemme/305986 to your computer and use it in GitHub Desktop.
Save rklemme/305986 to your computer and use it in GitHub Desktop.
#! ruby19
require 'thread'
Thread.abort_on_exception = true
def log(msg)
printf "%-30p %s\n", Thread.current, msg
end
class Semaphore
def initialize(val)
raise ArgumentError, "Wrong value %p" % val unless val >= 0
@val = val
@lock = Mutex.new
@positive = ConditionVariable.new
end
def acquire
@lock.synchronize do
while @val == 0
@positive.wait(@lock)
end
@val -= 1
end
end
def release
@lock.synchronize do
@val += 1
@positive.signal
end
end
def synchronize
acquire
begin
yield
ensure
release
end
end
end
# locking
puts <<MSG
Locking test
MSG
sem = Semaphore.new 2
th = (1..5).map do
Thread.new do
tc = Thread.current
10.times do
log "try"
sem.synchronize do
log "got"
end
log "released"
end
end
end
th.each {|t| t.join }
# signalling
puts <<MSG
Signalling test
MSG
sem = Semaphore.new 0
th = Thread.new do
5.times do
sem.acquire
log "got it"
end
end
10.times do
log "signalling"
sem.release
end
th.join
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment