Sha256: 63dedd44d4ac680eb2e24710d326ee20de0ecf8425af9e030d491e618e2ca86f

Contents?: true

Size: 1.56 KB

Versions: 4

Compression:

Stored size: 1.56 KB

Contents

require "thread"

module Celluloid
  class Group
    class Spawner < Group
      attr_accessor :finalizer

      def initialize
        super
      end

      def get(&block)
        assert_active
        fail ArgumentError.new("No block sent to Spawner.get()") unless block_given?
        instantiate block
      end

      def shutdown
        @running = false
        queue = []
        @mutex.synchronize do
          loop do
            break if @group.empty?
            th = @group.shift
            th.kill
            queue << th
          end
        end
        Thread.pass unless queue.empty?
        loop do
          break if queue.empty?
          queue.pop.join
        end
      end

      def idle?
        to_a.select { |t| t[:celluloid_thread_state] == :running }.empty?
      end

      def busy?
        to_a.select { |t| t[:celluloid_thread_state] == :running }.any?
      end

      private

      def instantiate(proc)
        thread = Thread.new do
          Thread.current[:celluloid_thread_state] = :running
          begin
            proc.call
          rescue ::Exception => ex
            Internals::Logger.crash("thread crashed", ex)
            Thread.current[:celluloid_thread_state] = :error
          ensure
            unless Thread.current[:celluloid_thread_state] == :error
              Thread.current[:celluloid_thread_state] = :finished
            end
            @mutex.synchronize { @group.delete Thread.current }
            Thread.exit
          end
        end

        @mutex.synchronize { @group << thread }
        thread
      end
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
celluloid-0.17.4 lib/celluloid/group/spawner.rb
celluloid-0.18.0.pre lib/celluloid/group/spawner.rb
celluloid-0.17.3 lib/celluloid/group/spawner.rb
celluloid-0.17.2 lib/celluloid/group/spawner.rb