Module: MonitorMixin

Included in:
Monitor
Defined in:
lib/monitor.rb

Overview

Adds monitor functionality to an arbitrary object by mixing the module with include. For example:

require 'monitor.rb'

buf = []
buf.extend(MonitorMixin)
empty_cond = buf.new_cond

# consumer
Thread.start do
 loop do
   buf.synchronize do
     empty_cond.wait_while { buf.empty? }
     print buf.shift
   end
 end
end

# producer
while line = ARGF.gets
 buf.synchronize do
   buf.push(line)
   empty_cond.signal
 end
end

The consumer thread waits for the producer thread to push a line to buf while buf.empty?, and the producer thread (main thread) reads a line from ARGF and push it to buf, then call empty_cond.signal.

Defined Under Namespace

Classes: ConditionVariable

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.extend_object(obj) ⇒ Object



182
183
184
185
# File 'lib/monitor.rb', line 182

def self.extend_object(obj)
  super(obj)
  obj.instance_eval {mon_initialize()}
end

Instance Method Details

#mon_enterObject

Enters exclusive section.



209
210
211
212
213
214
# File 'lib/monitor.rb', line 209

def mon_enter
  Thread.critical = true
  mon_acquire(@mon_entering_queue)
  @mon_count += 1
  Thread.critical = false
end

#mon_exitObject

Leaves exclusive section.



219
220
221
222
223
224
225
226
227
228
# File 'lib/monitor.rb', line 219

def mon_exit
  mon_check_owner
  Thread.critical = true
  @mon_count -= 1
  if @mon_count == 0
    mon_release
  end
  Thread.critical = false
  Thread.pass
end

#mon_synchronizeObject Also known as: synchronize

Enters exclusive section and executes the block. Leaves the exclusive section automatically when the block exits. See example under MonitorMixin.



235
236
237
238
239
240
241
242
# File 'lib/monitor.rb', line 235

def mon_synchronize
  mon_enter
  begin
    yield
  ensure
    mon_exit
  end
end

#mon_try_enterObject Also known as: try_mon_enter

Attempts to enter exclusive section. Returns false if lock fails.



190
191
192
193
194
195
196
197
198
199
200
201
202
# File 'lib/monitor.rb', line 190

def mon_try_enter
  result = false
  Thread.critical = true
  if @mon_owner.nil?
    @mon_owner = Thread.current
  end
  if @mon_owner == Thread.current
    @mon_count += 1
    result = true
  end
  Thread.critical = false
  return result
end

#new_condObject

FIXME: This isn't documented in Nutshell.

Create a new condition variable for this monitor. This facilitates control of the monitor with #signal and #wait.



251
252
253
# File 'lib/monitor.rb', line 251

def new_cond
  return ConditionVariable.new(self)
end