Class: MultiProcessing::Semaphore

Inherits:
Object
  • Object
show all
Defined in:
lib/multiprocessing/semaphore.rb

Overview

Like Mutex but can manage multiple resources.

Note that Semaphore uses 4 pipes( 1 pipe, 1 Mutex, 1 ConditionVariable).

Examples:

require 'multiprocessing'

s = MultiProcessing::Semaphore.new 2
3.times do
  fork do
    s.synchronize do
      puts "pid: #{Process.pid}"
      sleep 1
    end
  end
end
Process.waitall
# => 2 processes prints its pid immediately
#    but the other does late.

Instance Method Summary collapse

Constructor Details

#initialize(count) ⇒ Semaphore

A new instance of Semaphore

Parameters:

  • count (Fixnum)

    is initial number of resource



36
37
38
39
40
41
# File 'lib/multiprocessing/semaphore.rb', line 36

def initialize count
  @count_pout, @count_pin = IO.pipe
  @count_pin.syswrite "1"*count
  @mutex = Mutex.new
  @cond = ConditionVariable.new
end

Instance Method Details

#countFixnum Also known as: value

Returns current number of resources.

Returns:

  • (Fixnum)


65
66
67
68
69
# File 'lib/multiprocessing/semaphore.rb', line 65

def count
  @mutex.synchronize do
    count_nonsynchronize
  end
end

#PSemaphore Also known as: lock, wait

Attempts to get the resource and wait if it isn’t available.

Returns:



78
79
80
81
82
83
84
85
86
# File 'lib/multiprocessing/semaphore.rb', line 78

def P
  @mutex.synchronize do
    while count_nonsynchronize == 0
      @cond.wait(@mutex)
    end
    @count_pout.readpartial 1
  end
  return self
end

#synchronizeObject

Obtains a resource, runs the block, and releases the resource when the block completes.

Returns:

  • (Object)

    returned value of the block



135
136
137
138
139
140
141
142
143
# File 'lib/multiprocessing/semaphore.rb', line 135

def synchronize
  self.P
  begin
    ret = yield
  ensure
    self.V
  end
  ret
end

#try_PBoolean Also known as: try_lock, try_wait

Attempts to get the resource and returns immediately Returns true if the resource granted.

Returns:

  • (Boolean)


97
98
99
100
101
102
103
104
105
106
# File 'lib/multiprocessing/semaphore.rb', line 97

def try_P
  begin
    @mutex.synchronize do
      @count_pout.read_nonblock 1
    end
    return true
  rescue Errno::EAGAIN
    return false
  end
end

#VSemaphore Also known as: signal, unlock, post

Releases the resource.

Returns:



116
117
118
119
120
121
122
123
124
# File 'lib/multiprocessing/semaphore.rb', line 116

def V
  MultiProcessing.try_handle_interrupt(RuntimeError => :never) do
    @mutex.synchronize do
      @count_pin.syswrite 1
      @cond.signal
    end
    self
  end
end