Class: IProcess

Inherits:
Object
  • Object
show all
Defined in:
lib/iprocess.rb,
lib/iprocess/version.rb

Constant Summary collapse

VERSION =
'6.0.0'

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(worker) ⇒ IProcess

Returns self.

Parameters:

  • worker (#call)

    The unit of work to execute in a subprocess.

Raises:

  • (ArgumentError)

    If a worker is not given.



61
62
63
64
65
66
67
68
69
# File 'lib/iprocess.rb', line 61

def initialize(worker)
  @worker  = worker
  @channel = nil
  @pid     = nil
  unless @worker.respond_to?(:call)
    raise ArgumentError,
          "Expected worker to implement #{@worker.class}#call"
  end
end

Class Method Details

.serializer#load, #dump

Returns the serializer used by IProcess.

Returns:

  • (#load, #dump)

    Returns the serializer used by IProcess.



9
10
11
# File 'lib/iprocess.rb', line 9

def self.serializer
  @serializer || Marshal
end

.serializer=(obj) ⇒ Object

Parameters:

  • obj (#load, #dump)

    Any object that implements #load, & #dump. Examples could be JSON & Marshal.



18
19
20
# File 'lib/iprocess.rb', line 18

def self.serializer=(obj)
  @serializer = obj
end

.spawn(number_of, obj = nil, &worker) ⇒ Object

Spawn one or more subprocesse(s).

@param [Integer] number_of The number of subprocesses to spawn.

@param [#call] worker The unit of work to execute in a subprocess.

@return [Array] The return value of the unit of work.

@example IProcess.spawn 2 do true end



39
40
41
# File 'lib/iprocess.rb', line 39

def self.spawn(number_of, obj = nil, &worker)
  fork(number_of, obj, &worker).map(&:result)
end

Instance Method Details

#executeFixnum

Executes a unit of work in a subprocess.

Returns:

  • (Fixnum)

    The process ID of the spawned subprocess.



77
78
79
80
# File 'lib/iprocess.rb', line 77

def execute
  @channel = IChannel.new IProcess.serializer
  @pid = fork { @channel.write(@worker.call) }
end

#resultObject

Returns the return value of the unit of work.

Returns:

  • (Object)

    Returns the return value of the unit of work.



86
87
88
89
90
91
# File 'lib/iprocess.rb', line 86

def result
  Process.wait(@pid)
  if @channel.readable?
    @channel.recv
  end
end