File: spawner.rb

package info (click to toggle)
ruby-celluloid 0.18.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 848 kB
  • sloc: ruby: 7,579; makefile: 10
file content (64 lines) | stat: -rw-r--r-- 1,551 bytes parent folder | download
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
module Celluloid
  class Group
    class Spawner < Group
      attr_accessor :finalizer

      def initialize
        super
      end

      def get(&block)
        assert_active
        raise ArgumentError, "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
            Thread.current[:celluloid_thread_state] = :finished unless Thread.current[:celluloid_thread_state] == :error
            @mutex.synchronize { @group.delete Thread.current }
            Thread.exit
          end
        end

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