class Async::IO::Trap

A cross-reactor/process notification pipe.

Public Class Methods

new(name) click to toggle source
# File lib/async/io/trap.rb, line 31
def initialize(name)
        @name = name
        @notifications = []
        
        @installed = false
        @mutex = Mutex.new
end

Public Instance Methods

async(parent: Task.current, **options, &block) click to toggle source

In order to avoid blocking the reactor, specify `transient: true` as an option.

# File lib/async/io/trap.rb, line 95
def async(parent: Task.current, **options, &block)
        parent.async(**options) do |task|
                self.wait(task: task, &block)
        end
end
default!() click to toggle source
# File lib/async/io/trap.rb, line 48
def default!
        Signal.trap(@name, :DEFAULT)
end
ignore!() click to toggle source

Ignore the trap within the current process. Can be invoked before forking and/or invoking `install!` to assert default behaviour.

# File lib/async/io/trap.rb, line 44
def ignore!
        Signal.trap(@name, :IGNORE)
end
install!() click to toggle source

Install the trap into the current process. Thread safe. @return [Boolean] whether the trap was installed or not. If the trap was already installed, returns nil.

# File lib/async/io/trap.rb, line 54
def install!
        return if @installed
        
        @mutex.synchronize do
                return if @installed
                
                Signal.trap(@name, &self.method(:trigger))
                
                @installed = true
        end
        
        return true
end
to_s() click to toggle source
# File lib/async/io/trap.rb, line 39
def to_s
        "\#<#{self.class} #{@name}>"
end
trap(task: Task.current, &block)

Deprecated.

Alias for: wait
trigger(signal_number = nil) click to toggle source

Signal all waiting tasks that the trap occurred. @return [void]

# File lib/async/io/trap.rb, line 103
def trigger(signal_number = nil)
        @notifications.each(&:signal)
end
wait(task: Task.current) { |task| ... } click to toggle source

Wait until the signal occurs. If a block is given, execute in a loop. @yield [Async::Task] the current task.

# File lib/async/io/trap.rb, line 70
def wait(task: Task.current, &block)
        task.annotate("waiting for signal #{@name}")
        
        notification = Notification.new
        @notifications << notification
        
        if block_given?
                while true
                        notification.wait
                        yield task
                end
        else
                notification.wait
        end
ensure
        if notification
                notification.close
                @notifications.delete(notification)
        end
end
Also aliased as: trap