Sha256: 1dd6e953f4bd5ea8880ad8c5e4851b31644ff02c4d270f7fefd2475044a2c57c

Contents?: true

Size: 1.4 KB

Versions: 6

Compression:

Stored size: 1.4 KB

Contents

require 'common/ext/stdout'
require 'stringio'
require 'thread'
require 'concurrent/atomic/mutex_semaphore'

module Bake
  module Multithread

    class Jobs

      def self.incThread
        @@semaphore.acquire
      end
      def self.decThread
        @@semaphore.release
      end
      def self.init_semaphore
        @@semaphore = ::Concurrent::MutexSemaphore.new(Bake.options.threads)
      end

      def initialize(jobs, &block)
        nr_of_threads = [Bake.options.threads, jobs.length].min
        @jobs = jobs
        @threads = []
        nr_of_threads.times do
          @threads << ::Thread.new(Thread.current[:stdout], Thread.current[:errorStream]) do |outStr, errStr|
            Thread.current[:stdout] = outStr
            Thread.current[:errorStream] = errStr
            begin
              Jobs.incThread()
              block.call(self)
            ensure
              Jobs.decThread()
            end
          end
        end
      end

      def failed
        @failed ||= false
      end
      def set_failed
        @failed = true
      end

      def get_next_or_nil
        the_next = nil
        mutex.synchronize {
          the_next = @jobs.shift
        }
        the_next
      end
      def join
        @threads.each{|t| while not t.join(2) do end}
      end
      def mutex
        @mutex ||= Mutex.new
      end
    end

  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
bake-toolkit-2.35.2 lib/multithread/job.rb
bake-toolkit-2.35.1 lib/multithread/job.rb
bake-toolkit-2.35.0 lib/multithread/job.rb
bake-toolkit-2.34.4 lib/multithread/job.rb
bake-toolkit-2.34.3 lib/multithread/job.rb
bake-toolkit-2.34.2 lib/multithread/job.rb