Module: MonitorMixin
- Defined in:
- lib/monitor.rb
Overview
Adds monitor functionality to an arbitrary object by mixing the module with include. For example:
require 'monitor'
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)
-
- (Object) mon_enter
Enters exclusive section.
-
- (Object) mon_exit
Leaves exclusive section.
-
- (Object) mon_synchronize
(also: #synchronize)
Enters exclusive section and executes the block.
-
- (Object) mon_try_enter
(also: #try_mon_enter)
Attempts to enter exclusive section.
-
- (Object) new_cond
Creates a new MonitorMixin::ConditionVariable associated with the receiver.
Class Method Details
+ (Object) extend_object(obj)
149 150 151 152 |
# File 'lib/monitor.rb', line 149 def self.extend_object(obj) super(obj) obj.__send__(:mon_initialize) end |
Instance Method Details
- (Object) mon_enter
Enters exclusive section.
173 174 175 176 177 178 179 |
# File 'lib/monitor.rb', line 173 def mon_enter if @mon_owner != Thread.current @mon_mutex.lock @mon_owner = Thread.current end @mon_count += 1 end |
- (Object) mon_exit
Leaves exclusive section.
184 185 186 187 188 189 190 191 |
# File 'lib/monitor.rb', line 184 def mon_exit mon_check_owner @mon_count -=1 if @mon_count == 0 @mon_owner = nil @mon_mutex.unlock end end |
- (Object) mon_synchronize Also known as: synchronize
Enters exclusive section and executes the block. Leaves the exclusive section automatically when the block exits. See example under MonitorMixin.
198 199 200 201 202 203 204 205 |
# File 'lib/monitor.rb', line 198 def mon_synchronize mon_enter begin yield ensure mon_exit end end |
- (Object) mon_try_enter Also known as: try_mon_enter
Attempts to enter exclusive section. Returns false if lock fails.
157 158 159 160 161 162 163 164 165 166 |
# File 'lib/monitor.rb', line 157 def mon_try_enter if @mon_owner != Thread.current unless @mon_mutex.try_lock return false end @mon_owner = Thread.current end @mon_count += 1 return true end |
- (Object) new_cond
Creates a new MonitorMixin::ConditionVariable associated with the receiver.
212 213 214 |
# File 'lib/monitor.rb', line 212 def new_cond return ConditionVariable.new(self) end |