lib/zold/thread_pool.rb in zold-0.22.0 vs lib/zold/thread_pool.rb in zold-0.22.1

- old
+ new

@@ -36,38 +36,10 @@ @log = log @threads = [] @start = Time.now end - # Run this code in many threads - def run(threads, set = (0..threads - 1).to_a) - raise "Number of threads #{threads} has to be positive" unless threads.positive? - list = set.dup - total = [threads, set.count].min - if total == 1 - list.each_with_index { |r, i| yield(r, i) } - elsif total.positive? - idx = Concurrent::AtomicFixnum.new - mutex = Mutex.new - latch = Concurrent::CountDownLatch.new(total) - total.times do |i| - add do - Thread.current.name = "#{@title}-#{i}" - loop do - r = mutex.synchronize { list.pop } - break if r.nil? - yield(r, idx.increment - 1) - end - ensure - latch.count_down - end - end - latch.wait - kill - end - end - # Add a new thread def add raise 'Block must be given to start()' unless block_given? latch = Concurrent::CountDownLatch.new(1) thread = Thread.start do @@ -97,13 +69,11 @@ end @log.debug("Stopping \"#{@title}\" thread pool with #{@threads.count} threads: \ #{@threads.map { |t| "#{t.name}/#{t.status}" }.join(', ')}...") start = Time.new begin - @threads.each do |t| - t.join(0.1) - end + join(0.1) ensure @threads.each do |t| (t.thread_variable_get(:kids) || []).each(&:kill) t.kill sleep(0.001) while t.alive? # I believe it's a bug in Ruby, this line fixes it @@ -114,9 +84,14 @@ end @log.debug("Thread pool \"#{@title}\" terminated all threads in #{Age.new(start)}, \ it was alive for #{Age.new(@start)}: #{@threads.map { |t| "#{t.name}/#{t.status}" }.join(', ')}") @threads.clear end + end + + # Is it empty and has no threads? + def empty? + @threads.empty? end # How many threads are in there def count @threads.count