Class: Stud::Task
- Inherits:
-
Object
- Object
- Stud::Task
- Defined in:
- lib/stud/task.rb
Overview
A Task spawns a thread to execute the given block. execution completion and result retrieval is done using the Task#wait method. A Task is run once and the thread exists upon block completion. A task and its underlying thread are not reusable.
Task does not provide a mean to force-interrupt a running task, it only provides the #stop! method to signal the task for a stop request. The task or code block can use the #stop? method to check for a stop request. Note that the #stop! and #stop? methods are thread safe.
Instance Attribute Summary collapse
-
#thread ⇒ Object
readonly
provide access to the underlying thread if ever needed.
Instance Method Summary collapse
-
#initialize(*args, &block) ⇒ Task
constructor
A new instance of Task.
-
#stop! ⇒ Object
stop! requests the task to stop.
-
#stop? ⇒ Boolean
(also: #interrupted?)
stop? returns true if this task stop! has been called See Stud.stop?.
-
#wait ⇒ Object, Exception
wait waits for the task thread to complete and return the block return value if the block raises an exception, this exception is propagated in this wait method.
Constructor Details
#initialize(*args, &block) ⇒ Task
Returns a new instance of Task.
17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
# File 'lib/stud/task.rb', line 17 def initialize(*args, &block) # A queue to receive the result of the block # TODO(sissel): Don't use a queue, just store it in an instance variable. @queue = Queue.new @thread = Thread.new(@queue, *args) do |queue, *args| begin result = block.call(*args) queue << [:return, result] rescue => e queue << [:exception, e] end end # thread end |
Instance Attribute Details
#thread ⇒ Object (readonly)
provide access to the underlying thread if ever needed.
15 16 17 |
# File 'lib/stud/task.rb', line 15 def thread @thread end |
Instance Method Details
#stop! ⇒ Object
stop! requests the task to stop. the Thread#wakeup method is also called so that a sleeping task is waked up and has a chance to verify the stop request using the #stop? method. also see Stud.stop!
51 52 53 |
# File 'lib/stud/task.rb', line 51 def stop! Stud.stop!(@thread) end |
#stop? ⇒ Boolean Also known as: interrupted?
stop? returns true if this task stop! has been called See Stud.stop?
58 59 60 |
# File 'lib/stud/task.rb', line 58 def stop? Stud.stop?(@thread) end |
#wait ⇒ Object, Exception
wait waits for the task thread to complete and return the block return value if the block raises an exception, this exception is propagated in this wait method.
36 37 38 39 40 41 42 43 44 45 46 |
# File 'lib/stud/task.rb', line 36 def wait @thread.join reason, result = @queue.pop if reason == :exception #raise StandardError.new(result) raise result else return result end end |