I've programmed a minimal parallel workers queue in Ruby, and I wanted to know if it's correct, and if there are simpler ways of implementing it.
I'm aware of the existence of MonitorMixin, but it won't save any code, I think.
The design is kept intentionally trivial (e.g. it uses Thread.abort_on_exception).
# Usage:
#
# queue = ParallelWorkersQueue.new( <threads> )
# queue.push { <operation_1> }
# queue.push { <operation_2> }
# queue.join
#
class ParallelWorkersQueue
def initialize( slots )
@max_slots = slots
@free_slots = slots
@mutex = Mutex.new
@condition_variable = ConditionVariable.new
Thread.abort_on_exception = true
end
def push( &task )
@mutex.synchronize do
while @free_slots == 0
@condition_variable.wait( @mutex )
end
@free_slots -= 1
end
Thread.new do
yield
@mutex.synchronize do
@free_slots += 1
@condition_variable.signal
end
end
end
def join
@mutex.synchronize do
while @free_slots < @max_slots
@condition_variable.wait( @mutex )
end
end
end
end