class Eldritch::Task

Runs a block in parallel and allows for interaction with said block

Attributes

thread[R]

@return [Thread] underlying ruby thread

Public Class Methods

new(&block) click to toggle source

Creates a new Task instance

Note: this method does not yield the block directly this is done by {#start}

@yield [Task] the task itself

# File lib/eldritch/task.rb, line 12
def initialize(&block)
  @block = block
end

Public Instance Methods

abort() click to toggle source

Forces the task to end

This kills the underlying thread. This is a dangerous call.

# File lib/eldritch/task.rb, line 49
def abort
  @thread.kill
  unset_thread_task
end
interrupt() click to toggle source

Interrupts the task

This is done by raising an {InterruptedError} in the task block. This can be caught to perform cleanup before exiting. Tasks started with {DSL#async} will automatically handle the exception and stop cleanly. You can still handle the exception yourself.

# File lib/eldritch/task.rb, line 60
def interrupt
  @thread.raise InterruptedError.new
  unset_thread_task
end
join() click to toggle source

Waits for the task to complete

# File lib/eldritch/task.rb, line 30
def join
  @thread.join
  unset_thread_task
end
start() click to toggle source

Starts the task

This will yield the task to the block passed in the constructor.

task = Eldritch::Task.new do |task|
  # do something
end
task.start  # calls the block in parallel
# File lib/eldritch/task.rb, line 24
def start
  @thread = Thread.new &@block
  @thread.eldritch_task = self
end
value() click to toggle source

The return value of the task

If the task is still running, it will block until it is done and then fetch the return value.

@return whatever the block returns

# File lib/eldritch/task.rb, line 40
def value
  val = @thread.value
  unset_thread_task
  val
end

Private Instance Methods

unset_thread_task() click to toggle source
# File lib/eldritch/task.rb, line 67
def unset_thread_task
  @thread.eldritch_task = nil
end