lib/thread/pool.rb in thread-0.1.3 vs lib/thread/pool.rb in thread-0.1.4
- old
+ new
@@ -98,11 +98,11 @@
self
end
end
- attr_reader :min, :max, :spawned
+ attr_reader :min, :max, :spawned, :waiting
# Create the pool with minimum and maximum threads.
#
# The pool will start with the minimum amount of threads created and will
# spawn new threads until the max is reached in case of need.
@@ -117,11 +117,11 @@
@cond = ConditionVariable.new
@mutex = Mutex.new
@done = ConditionVariable.new
@done_mutex = Mutex.new
-
+
@todo = []
@workers = []
@timeouts = {}
@spawned = 0
@@ -198,11 +198,33 @@
@done_mutex.synchronize {
return if done?
@done.wait @done_mutex
}
end
+
+ # Check if there are idle workers.
+ def idle?
+ @todo.length < @waiting
+ end
+ # Process Block when there is a idle worker if not block its returns
+ def idle (&block)
+ while !idle?
+ @done_mutex.synchronize {
+ break if idle?
+ @done.wait @done_mutex
+ }
+ end
+
+ unless block
+ return
+ end
+
+ process &block
+
+ end
+
# Add a task to the pool which will execute the block with the given
# argument.
#
# If no block is passed the default block will be used if present, an
# ArgumentError will be raised otherwise.
@@ -412,17 +434,16 @@
}
end
def report_done
@done_mutex.synchronize {
- @done.broadcast if done?
+ @done.broadcast if done? or idle?
}
end
-
end
class Thread
# Helper to create a pool.
def self.pool (*args, &block)
Thread::Pool.new(*args, &block)
end
-end
+end
\ No newline at end of file