Class: Minx::Process

Inherits:
Object
  • Object
show all
Defined in:
lib/minx/process.rb

Overview

A process is the core concurrency primitive in Minx.

Processes run concurrently and independently. In order to synchronize and organize processes you need to use channels -- these synchronously transmit messages between two processes, making them ideal for communication and synchronization.

Oftentimes, you need not work directly with the Process objects, but can use the methods on the Minx module directly, such as spawn, yield, and join.

See Also:

Class Attribute Summary (collapse)

Instance Method Summary (collapse)

Constructor Details

- (Process) initialize(&block)

Initialize a new process.

The process is not spawned when instantiated; you'll need to call #spawn manually. Call Minx.spawn to immediately spawn a new process.

Examples:

Creating a new process

p = Minx::Process.new { 1 + 1 }
p.spawn

Raises:

  • (ArgumentError)

    unless a block is given

See Also:



32
33
34
35
36
37
# File 'lib/minx/process.rb', line 32

def initialize(&block)
  raise ArgumentError unless block_given?

  @supervisors = []
  @block = block
end

Class Attribute Details

+ (Object) current

The currently running process.



80
81
82
# File 'lib/minx/process.rb', line 80

def current
  @current
end

Instance Method Details

- (Boolean) finished?

Whether the process has finished execution.

Returns:

  • (Boolean)

    true if the process has terminated, false otherwise



70
71
72
# File 'lib/minx/process.rb', line 70

def finished?
  !@fiber.alive?
end

- (Object) spawn

Spawn the process.

The process will immediately take over execution, and the current fiber will yield.

Raises:

  • (ProcessError)

    if the process has already been spawned



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/minx/process.rb', line 45

def spawn
  raise ProcessError if defined?(@fiber)

  @fiber = Fiber.new do
    begin
      @block.call
    rescue Exception => e
      if @supervisors.empty?
        $stderr.puts("#{e.class}: #{e.message}")
        $stderr.puts(e.backtrace)
        exit(-1) if Minx.abort_on_exception
      else
        @supervisors.each {|s| s.resume(e, self) }
      end
    end
  end

  @fiber.resume

  return self
end

- (Object) supervise



74
75
76
# File 'lib/minx/process.rb', line 74

def supervise
  @supervisors << Fiber.current
end