Debian Codegraph @

ext/monitor/lib/monitor.rb

raw
1 # frozen_string_literal: false
2 # = monitor.rb
3 #
4 # Copyright (C) 2001 Shugo Maeda <[email protected]>
5 #
6 # This library is distributed under the terms of the Ruby license.
7 # You can freely distribute/modify this library.
8 #
9
10 require 'monitor.so'
11
12 #
13 # In concurrent programming, a monitor is an object or module intended to be
14 # used safely by more than one thread. The defining characteristic of a
15 # monitor is that its methods are executed with mutual exclusion. That is, at
16 # each point in time, at most one thread may be executing any of its methods.
17 # This mutual exclusion greatly simplifies reasoning about the implementation
18 # of monitors compared to reasoning about parallel code that updates a data
19 # structure.
20 #
21 # You can read more about the general principles on the Wikipedia page for
22 # Monitors[https://en.wikipedia.org/wiki/Monitor_%28synchronization%29].
23 #
24 # == Examples
25 #
26 # === Simple object.extend
27 #
28 # require 'monitor.rb'
29 #
30 # buf = []
31 # buf.extend(MonitorMixin)
32 # empty_cond = buf.new_cond
33 #
34 # # consumer
35 # Thread.start do
36 # loop do
37 # buf.synchronize do
38 # empty_cond.wait_while { buf.empty? }
39 # print buf.shift
40 # end
41 # end
42 # end
43 #
44 # # producer
45 # while line = ARGF.gets
46 # buf.synchronize do
47 # buf.push(line)
48 # empty_cond.signal
49 # end
50 # end
51 #
52 # The consumer thread waits for the producer thread to push a line to buf
53 # while <tt>buf.empty?</tt>. The producer thread (main thread) reads a
54 # line from ARGF and pushes it into buf then calls <tt>empty_cond.signal</tt>
55 # to notify the consumer thread of new data.
56 #
57 # === Simple Class include
58 #
59 # require 'monitor'
60 #
61 # class SynchronizedArray < Array
62 #
63 # include MonitorMixin
64 #
65 # def initialize(*args)
66 # super(*args)
67 # end
68 #
69 # alias :old_shift :shift
70 # alias :old_unshift :unshift
71 #
72 # def shift(n=1)
73 # self.synchronize do
74 # self.old_shift(n)
75 # end
76 # end
77 #
78 # def unshift(item)
79 # self.synchronize do
80 # self.old_unshift(item)
81 # end
82 # end
83 #
84 # # other methods ...
85 # end
86 #
87 # +SynchronizedArray+ implements an Array with synchronized access to items.
88 # This Class is implemented as subclass of Array which includes the
89 # MonitorMixin module.
90 #
91 module MonitorMixin
92 #
93 # FIXME: This isn't documented in Nutshell.
94 #
95 # Since MonitorMixin.new_cond returns a ConditionVariable, and the example
96 # above calls while_wait and signal, this class should be documented.
97 #
98 class ConditionVariable
99 #
100 # Releases the lock held in the associated monitor and waits; reacquires the lock on wakeup.
101 #
102 # If +timeout+ is given, this method returns after +timeout+ seconds passed,
103 # even if no other thread doesn't signal.
104 #
105 def wait(timeout = nil)
106 @monitor.mon_check_owner
107 @monitor.wait_for_cond(@cond, timeout)
108 end
109
110 #
111 # Calls wait repeatedly while the given block yields a truthy value.
112 #
113 def wait_while
114 while yield
115 wait
116 end
117 end
118
119 #
120 # Calls wait repeatedly until the given block yields a truthy value.
121 #
122 def wait_until
123 until yield
124 wait
125 end
126 end
127
128 #
129 # Wakes up the first thread in line waiting for this lock.
130 #
131 def signal
132 @monitor.mon_check_owner
133 @cond.signal
134 end
135
136 #
137 # Wakes up all threads waiting for this lock.
138 #
139 def broadcast
140 @monitor.mon_check_owner
141 @cond.broadcast
142 end
143
144 private
145
146 def initialize(monitor)
147 @monitor = monitor
148 @cond = Thread::ConditionVariable.new
149 end
150 end
151
152 def self.extend_object(obj)
153 super(obj)
154 obj.__send__(:mon_initialize)
155 end
156
157 #
158 # Attempts to enter exclusive section. Returns +false+ if lock fails.
159 #
160 def mon_try_enter
161 @mon_data.try_enter
162 end
163 # For backward compatibility
164 alias try_mon_enter mon_try_enter
165
166 #
167 # Enters exclusive section.
168 #
169 def mon_enter
170 @mon_data.enter
171 end
172
173 #
174 # Leaves exclusive section.
175 #
176 def mon_exit
177 mon_check_owner
178 @mon_data.exit
179 end
180
181 #
182 # Returns true if this monitor is locked by any thread
183 #
184 def mon_locked?
185 @mon_data.mon_locked?
186 end
187
188 #
189 # Returns true if this monitor is locked by current thread.
190 #
191 def mon_owned?
192 @mon_data.mon_owned?
193 end
194
195 #
196 # Enters exclusive section and executes the block. Leaves the exclusive
197 # section automatically when the block exits. See example under
198 # +MonitorMixin+.
199 #
200 def mon_synchronize(&b)
201 @mon_data.synchronize(&b)
202 end
203 alias synchronize mon_synchronize
204
205 #
206 # Creates a new MonitorMixin::ConditionVariable associated with the
207 # Monitor object.
208 #
209 def new_cond
210 unless defined?(@mon_data)
211 mon_initialize
212 @mon_initialized_by_new_cond = true
213 end
214 return ConditionVariable.new(@mon_data)
215 end
216
217 private
218
219 # Use <tt>extend MonitorMixin</tt> or <tt>include MonitorMixin</tt> instead
220 # of this constructor. Have look at the examples above to understand how to
221 # use this module.
222 def initialize(...)
223 super
224 mon_initialize
225 end
226
227 # Initializes the MonitorMixin after being included in a class or when an
228 # object has been extended with the MonitorMixin
229 def mon_initialize
230 if defined?(@mon_data)
231 if defined?(@mon_initialized_by_new_cond)
232 return # already initialized.
233 elsif @mon_data_owner_object_id == self.object_id
234 raise ThreadError, "already initialized"
235 end
236 end
237 @mon_data = ::Monitor.new
238 @mon_data_owner_object_id = self.object_id
239 end
240
241 def mon_check_owner
242 @mon_data.mon_check_owner
243 end
244 end
245
246 # Use the Monitor class when you want to have a lock object for blocks with
247 # mutual exclusion.
248 #
249 # require 'monitor'
250 #
251 # lock = Monitor.new
252 # lock.synchronize do
253 # # exclusive access
254 # end
255 #
256 class Monitor
257 def new_cond
258 ::MonitorMixin::ConditionVariable.new(self)
259 end
260
261 # for compatibility
262 alias try_mon_enter try_enter
263 alias mon_try_enter try_enter
264 alias mon_enter enter
265 alias mon_exit exit
266 alias mon_synchronize synchronize
267 end
268
269 # Documentation comments:
270 # - All documentation comes from Nutshell.
271 # - MonitorMixin.new_cond appears in the example, but is not documented in
272 # Nutshell.
273 # - All the internals (internal modules Accessible and Initializable, class
274 # ConditionVariable) appear in RDoc. It might be good to hide them, by
275 # making them private, or marking them :nodoc:, etc.
276 # - RDoc doesn't recognise aliases, so we have mon_synchronize documented, but
277 # not synchronize.
278 # - mon_owner is in Nutshell, but appears as an accessor in a separate module
279 # here, so is hard/impossible to RDoc. Some other useful accessors
280 # (mon_count and some queue stuff) are also in this module, and don't appear
281 # directly in the RDoc output.
282 # - in short, it may be worth changing the code layout in this file to make the
283 # documentation easier