File: thread_handle.rb

package info (click to toggle)
ruby-celluloid-essentials 0.20.5-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 240 kB
  • sloc: ruby: 1,084; makefile: 5
file content (52 lines) | stat: -rw-r--r-- 1,472 bytes parent folder | download | duplicates (3)
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
module Celluloid
  module Internals
    # An abstraction around threads from the InternalPool which ensures we don't
    # accidentally do things to threads which have been returned to the pool,
    # such as, say, killing them
    class ThreadHandle
      def initialize(actor_system, role = nil)
        @mutex = Mutex.new
        @join  = ConditionVariable.new

        @thread = actor_system.get_thread do
          Thread.current.role = role
          begin
            yield
          ensure
            @mutex.synchronize do
              @thread = nil
              @join.broadcast
            end
          end
        end
      end

      # Is the thread running?
      def alive?
        @mutex.synchronize { @thread.alive? if @thread }
      end

      # Forcibly kill the thread
      def kill
        !!@mutex.synchronize { @thread.kill if @thread }
        self
      end

      # Join to a running thread, blocking until it terminates
      def join(limit = nil)
        fail ThreadError, "Target thread must not be current thread" if @thread == Thread.current
        @mutex.synchronize { @join.wait(@mutex, limit) if @thread }
        self
      end

      # Obtain the backtrace for this thread
      def backtrace
        @thread.backtrace
      rescue NoMethodError
        # undefined method `backtrace' for nil:NilClass
        # Swallow this in case this ThreadHandle was terminated and @thread was
        # set to nil
      end
    end
  end
end