lib/workers/task_group.rb in workers-0.1.0 vs lib/workers/task_group.rb in workers-0.1.1
- old
+ new
@@ -8,11 +8,12 @@
def initialize(options = {})
@logger = Workers::LogProxy.new(options[:logger])
@pool = options[:pool] || Workers.pool
@state = :initialized
@tasks = []
- @lock = Mutex.new
+ @internal_lock = Mutex.new
+ @external_lock = Mutex.new
@finished_count = 0
@conditional = ConditionVariable.new
return nil
end
@@ -33,16 +34,16 @@
state!(:initialized)
@state = :running
@run_thread = Thread.current
- @lock.synchronize do
+ @internal_lock.synchronize do
@tasks.each do |task|
@pool.perform { task.run }
end
- @conditional.wait(@lock)
+ @conditional.wait(@internal_lock)
end
return @tasks.all? { |t| t.succeeded? }
end
@@ -72,10 +73,18 @@
end
return tasks.map { |t| t.result }
end
+ # Convenient mutex to be used by a users's task code that needs serializing.
+ # This should NEVER be used by TaskGroup code (use the @internal_lock instead);
+ def synchronize(&block)
+ @external_lock.synchronize { block.call }
+
+ return nil
+ end
+
private
def state!(*args)
unless args.include?(@state)
raise "Invalid state (#{@state})."
@@ -83,10 +92,10 @@
return nil
end
def finished(task)
- @lock.synchronize do
+ @internal_lock.synchronize do
@finished_count += 1
@conditional.signal if @finished_count >= @tasks.count
end
return nil