Class: WGPU::AsyncTask

Inherits:
Object
  • Object
show all
Defined in:
lib/wgpu/async_task.rb,
sig/wgpu.rbs

Instance Method Summary collapse

Constructor Details

#initialize { ... } ⇒ AsyncTask

Starts a background task that evaluates the given block.

Yields:

Yield Returns:

  • (A)

Raises:

  • (ArgumentError)

    if no block is supplied



9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/wgpu/async_task.rb', line 9

def initialize(&block)
  raise ArgumentError, "block is required" unless block

  @value = nil
  @error = nil
  @thread = Thread.new do
    begin
      @value = block.call
    rescue StandardError => e
      @error = e
    end
  end
end

Instance Method Details

#complete?Boolean

Reports whether the task has finished.

Returns:

  • (Boolean)


55
56
57
# File 'lib/wgpu/async_task.rb', line 55

def complete?
  !@thread.alive?
end

#errorStandardError?

Returns the exception raised by the task, if any.

Returns:

  • (StandardError, nil)


67
68
69
70
71
72
# File 'lib/wgpu/async_task.rb', line 67

def error
  value
  nil
rescue StandardError => e
  e
end

#pending?Boolean

Reports whether the task is still running.

Returns:

  • (Boolean)


61
62
63
# File 'lib/wgpu/async_task.rb', line 61

def pending?
  @thread.alive?
end

#then {|value| ... } ⇒ AsyncTask

Creates a task that transforms this task's result.

Yield Parameters:

  • value (Object)

    completed task result

Returns:



47
48
49
50
51
# File 'lib/wgpu/async_task.rb', line 47

def then(&block)
  AsyncTask.new do
    block.call(value)
  end
end

#value(timeout: nil) ⇒ Object

Waits for and returns the task result.

Parameters:

  • timeout (Numeric, nil) (defaults to: nil)

    maximum number of seconds to wait

  • timeout: (Numeric, nil) (defaults to: nil)

Returns:

  • (Object)

    block result

Raises:

  • (StandardError)

    re-raises an exception raised by the block



37
38
39
40
41
42
# File 'lib/wgpu/async_task.rb', line 37

def value(timeout: nil)
  wait(timeout: timeout)
  raise @error if @error

  @value
end

#wait(timeout: nil) ⇒ AsyncTask

Waits until the task finishes.

Parameters:

  • timeout (Numeric, nil) (defaults to: nil)

    maximum number of seconds to wait

  • timeout: (Numeric, nil) (defaults to: nil)

Returns:

Raises:

  • (Timeout::Error)

    if the task does not finish in time



27
28
29
30
31
# File 'lib/wgpu/async_task.rb', line 27

def wait(timeout: nil)
  joined = timeout ? @thread.join(timeout) : @thread.join
  raise Timeout::Error, "async task timeout" unless joined
  self
end