summaryrefslogtreecommitdiff
path: root/lib/bundler/parallel_workers/worker.rb
blob: 6e22eb4ce7091c5019e6ac73ce9f5da9cd9be004 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
module Bundler
  module ParallelWorkers
    class Worker
      POISON = Object.new

      class WrappedException < StandardError
        attr_reader :exception
        def initialize(exn)
          @exception = exn
        end
      end

      # Creates a worker pool of specified size
      #
      # @param size [Integer] Size of pool
      # @param func [Proc] job to run in inside the worker pool
      def initialize(size, func)
        @request_queue = Queue.new
        @response_queue = Queue.new
        prepare_workers size, func
        prepare_threads size
      end

      # Enque a request to be executed in the worker pool
      #
      # @param obj [String] mostly it is name of spec that should be downloaded
      def enq(obj)
        @request_queue.enq obj
      end

      # Retrieves results of job function being executed in worker pool
      def deq
        result = @response_queue.deq
        if WrappedException === result
          raise result.exception
        end
        result
      end

      # Stop the forked workers and started threads
      def stop
        stop_threads
        stop_workers
      end

      private
      # Stop the worker threads by sending a poison object down the request queue 
      # so as worker threads after retrieving it, shut themselves down
      def stop_threads
        @threads.each do
          @request_queue.enq POISON
        end
        @threads.each do |thread|
          thread.join
        end
      end

      # To be overridden by child classes
      def prepare_threads(size)
      end

      # To be overridden by child classes
      def stop_workers
      end

    end
  end
end