Class: IProcess

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

Constant Summary collapse

VERSION =
'5.1.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.



80
81
82
83
84
85
86
87
88
# File 'lib/iprocess.rb', line 80

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

.spawn!(number_of, inbox, obj = nil, &worker) ⇒ Array<IProcess>

Spawn one or more subprocesse(s) asynchronously.

Parameters:

  • inbox (#recv)

    An object who can receive messages through the #recv method.

Returns:



54
55
56
57
58
59
60
# File 'lib/iprocess.rb', line 54

def self.spawn!(number_of, inbox, obj = nil, &worker)
  forks = fork number_of, obj, &worker
  forks.each do |subprocess|
    t = Thread.new { inbox.recv subprocess.result }
    at_exit { t.join }
  end
end

Instance Method Details

#executeFixnum

Executes a unit of work in a subprocess.

Returns:

  • (Fixnum)

    The process ID of the spawned subprocess.



96
97
98
99
# File 'lib/iprocess.rb', line 96

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.



105
106
107
108
# File 'lib/iprocess.rb', line 105

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