U:RDoc::NormalModule[iI"MonitorMixin:EF@0o:RDoc::Markup::Document:@parts[o;;[o:RDoc::Markup::Paragraph;[I"PIn concurrent programming, a monitor is an object or module intended to be ;TI"Lused safely by more than one thread. The defining characteristic of a ;TI"Rmonitor is that its methods are executed with mutual exclusion. That is, at ;TI"Qeach point in time, at most one thread may be executing any of its methods. ;TI"QThis mutual exclusion greatly simplifies reasoning about the implementation ;TI"Oof monitors compared to reasoning about parallel code that updates a data ;TI"structure.;To:RDoc::Markup::BlankLine o; ;[I"NYou can read more about the general principles on the Wikipedia page for ;TI"IMonitors[http://en.wikipedia.org/wiki/Monitor_%28synchronization%29];T@S:RDoc::Markup::Heading:
leveli: textI"
Examples;T@S;;i;
I"Simple object.extend;T@o:RDoc::Markup::Verbatim;[I"require 'monitor.rb'
;TI"
;TI"buf = []
;TI"buf.extend(MonitorMixin)
;TI"empty_cond = buf.new_cond
;TI"
;TI"# consumer
;TI"Thread.start do
;TI" loop do
;TI" buf.synchronize do
;TI"0 empty_cond.wait_while { buf.empty? }
;TI" print buf.shift
;TI"
end
;TI" end
;TI" end
;TI"
;TI"# producer
;TI"while line = ARGF.gets
;TI" buf.synchronize do
;TI" buf.push(line)
;TI" empty_cond.signal
;TI" end
;TI" end
;T:@format0o; ;[ I"MThe consumer thread waits for the producer thread to push a line to buf ;TI"Kwhile buf.empty?. The producer thread (main thread) reads a ;TI"Qline from ARGF and pushes it into buf then calls empty_cond.signal ;TI"/to notify the consumer thread of new data.;T@S;;i;
I"Simple Class include;T@o;;[ I"require 'monitor'
;TI"
;TI"%class SynchronizedArray < Array
;TI"
;TI" include MonitorMixin
;TI"
;TI" def initialize(*args)
;TI" super(*args)
;TI" end
;TI"
;TI" alias :old_shift :shift
;TI"# alias :old_unshift :unshift
;TI"
;TI" def shift(n=1)
;TI" self.synchronize do
;TI" self.old_shift(n)
;TI"
end
;TI" end
;TI"
;TI" def unshift(item)
;TI" self.synchronize do
;TI"" self.old_unshift(item)
;TI"
end
;TI" end
;TI"
;TI" # other methods ...
;TI" end
;T;0o; ;[I"P+SynchronizedArray+ implements an Array with synchronized access to items. ;TI"GThis Class is implemented as subclass of Array which includes the ;TI"MonitorMixin module.;T:
@fileI"lib/monitor.rb;T:0@omit_headings_from_table_of_contents_below0;0;0[ [ [ [[I"
class;T[[:public[[I"extend_object;FI"lib/monitor.rb;T[I"new;T@m[:protected[ [:private[ [I"
instance;T[[;[[I"mon_enter;F@m[I"
mon_exit;F@m[I"mon_synchronize;F@m[I"mon_try_enter;F@m[I"
new_cond;F@m[I"synchronize;F@m[I"try_mon_enter;F@m[;[ [;[ [I"mon_check_owner;F@m[I"mon_enter_for_cond;F@m[I"mon_exit_for_cond;F@m[I"mon_initialize;F@m[ [U:RDoc::Context::Section[i 0o;;[ ;0;0[@a@acRDoc::TopLevel