Skip to content

Instantly share code, notes, and snippets.

@robholland
Created April 28, 2009 16:43
Show Gist options
  • Save robholland/103257 to your computer and use it in GitHub Desktop.
Save robholland/103257 to your computer and use it in GitHub Desktop.
#!/usr/bin/env jruby
require 'monitor'
class WorkerToken
end
class WorkerGroup
LIMIT = 1
def initialize
@worker_mutex ||= Monitor.new
@worker_queue ||= @worker_mutex.new_cond
@worker_slots ||= []
end
def get_slot
@worker_mutex.synchronize do
loop do
if @worker_slots.size >= LIMIT
@worker_queue.wait
end
token = WorkerToken.new
@worker_slots << token
return token
end
end
end
def free_slot(token)
@worker_mutex.synchronize do
if @worker_slots.delete(token)
@worker_queue.signal
end
end
end
end
group = WorkerGroup.new
t1 = Thread.new do
token_1 = group.get_slot
Thread.new { sleep 1; group.free_slot(token_1) }
token_2 = group.get_slot
Thread.new { sleep 1; group.free_slot(token_2) }
end
t2 = Thread.new do
token_3 = group.get_slot
Thread.new { sleep 1; group.free_slot(token_3) }
token_4 = group.get_slot
Thread.new { sleep 1; group.free_slot(token_4) }
end
t1.join
t2.join
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment