VirtualBox

source: vbox/trunk/src/VBox/Main/include/AutoLock.h@ 7992

Last change on this file since 7992 was 7992, checked in by vboxsync, 17 years ago

Main: Implemented true AutoReaderLock (#2768).

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 38.8 KB
Line 
1/** @file
2 *
3 * AutoLock: smart critical section wrapper
4 */
5
6/*
7 * Copyright (C) 2006-2008 innotek GmbH
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 */
17
18#ifndef ____H_AUTOLOCK
19#define ____H_AUTOLOCK
20
21#include <iprt/cdefs.h>
22#include <iprt/types.h>
23#include <iprt/critsect.h>
24#include <iprt/thread.h>
25#include <iprt/semaphore.h>
26
27#include <iprt/assert.h>
28
29#if defined(DEBUG)
30# include <iprt/asm.h> // for ASMReturnAddress
31#endif
32
33namespace util
34{
35
36/**
37 * Abstract lock operations. See LockHandle and AutoLock for details.
38 */
39class LockOps
40{
41public:
42
43 virtual ~LockOps() {}
44
45 virtual void lock() = 0;
46 virtual void unlock() = 0;
47};
48
49/**
50 * Read lock operations. See LockHandle and AutoLock for details.
51 */
52class ReadLockOps : public LockOps
53{
54public:
55
56 /**
57 * Requests a read (shared) lock.
58 */
59 virtual void lockRead() = 0;
60
61 /**
62 * Releases a read (shared) lock ackquired by lockRead().
63 */
64 virtual void unlockRead() = 0;
65
66 // LockOps interface
67 void lock() { lockRead(); }
68 void unlock() { unlockRead(); }
69};
70
71/**
72 * Write lock operations. See LockHandle and AutoLock for details.
73 */
74class WriteLockOps : public LockOps
75{
76public:
77
78 /**
79 * Requests a write (exclusive) lock.
80 */
81 virtual void lockWrite() = 0;
82
83 /**
84 * Releases a write (exclusive) lock ackquired by lockWrite().
85 */
86 virtual void unlockWrite() = 0;
87
88 // LockOps interface
89 void lock() { lockWrite(); }
90 void unlock() { unlockWrite(); }
91};
92
93/**
94 * Abstract read/write semaphore handle.
95 *
96 * This is a base class to implement semaphores that provide read/write locking.
97 * Subclasses must implement all pure virtual methods of this class together
98 * with pure methods of ReadLockOps and WriteLockOps classes.
99 *
100 * See the AutoLock class documentation for the detailed description of read and
101 * write locks.
102 */
103class LockHandle : protected ReadLockOps, protected WriteLockOps
104{
105public:
106
107 LockHandle() {}
108 virtual ~LockHandle() {}
109
110 /**
111 * Returns @c true if the current thread holds a write lock on this
112 * read/write semaphore. Intended for debugging only.
113 */
114 virtual bool isLockedOnCurrentThread() const = 0;
115
116 /**
117 * Returns the current write lock level of this semaphore. The lock level
118 * determines the number of nested #lock() calls on the given semaphore
119 * handle.
120 *
121 * Note that this call is valid only when the current thread owns a write
122 * lock on the given semaphore handle and will assert otherwise.
123 */
124 virtual uint32_t writeLockLevel() const = 0;
125
126 /**
127 * Returns an interface to read lock operations of this semaphore.
128 * Used by constructors of AutoMultiLockN classes.
129 */
130 LockOps *rlock() { return (ReadLockOps *) this; }
131
132 /**
133 * Returns an interface to write lock operations of this semaphore.
134 * Used by constructors of AutoMultiLockN classes.
135 */
136 LockOps *wlock() { return (WriteLockOps *) this; }
137
138private:
139
140 DECLARE_CLS_COPY_CTOR_ASSIGN_NOOP (LockHandle)
141
142 friend class AutoLock;
143 friend class AutoReaderLock;
144};
145
146/**
147 * Full-featured read/write semaphore handle implementation.
148 *
149 * This is an auxiliary base class for classes that need full-featured
150 * read/write locking as described in the AutoLock class documentation.
151 * Instances of classes inherited from this class can be passed as arguments to
152 * the AutoLock and AutoReaderLock constructors.
153 */
154class RWLockHandle : public LockHandle
155{
156public:
157
158 RWLockHandle();
159 virtual ~RWLockHandle();
160
161 bool isLockedOnCurrentThread() const;
162
163private:
164
165 DECLARE_CLS_COPY_CTOR_ASSIGN_NOOP (RWLockHandle)
166
167 void lockWrite();
168 void unlockWrite();
169 void lockRead();
170 void unlockRead();
171
172 uint32_t writeLockLevel() const;
173
174 mutable RTCRITSECT mCritSect;
175 RTSEMEVENT mGoWriteSem;
176 RTSEMEVENTMULTI mGoReadSem;
177
178 RTTHREAD mWriteLockThread;
179
180 uint32_t mReadLockCount;
181 uint32_t mWriteLockLevel;
182 uint32_t mWriteLockPending;
183};
184
185/**
186 * Write-only semaphore handle implementation.
187 *
188 * This is an auxiliary base class for classes that need write-only (exclusive)
189 * locking and do not need read (shared) locking. This implementation uses a
190 * cheap and fast critical section for both lockWrite() and lockRead() methods
191 * which makes a lockRead() call fully equivalent to the lockWrite() call and
192 * therefore makes it pointless to use instahces of this class with
193 * AutoReaderLock instances -- shared locking will not be possible anyway and
194 * any call to lock() will block if there are lock owners on other threads.
195 *
196 * Use with care only when absolutely sure that shared locks are not necessary.
197 */
198class WriteLockHandle : public LockHandle
199{
200public:
201
202 WriteLockHandle()
203 {
204 RTCritSectInit (&mCritSect);
205 }
206
207 virtual ~WriteLockHandle()
208 {
209 RTCritSectDelete (&mCritSect);
210 }
211
212 bool isLockedOnCurrentThread() const
213 {
214 return RTCritSectIsOwner (&mCritSect);
215 }
216
217private:
218
219 DECLARE_CLS_COPY_CTOR_ASSIGN_NOOP (WriteLockHandle)
220
221 void lockWrite()
222 {
223#if defined(DEBUG)
224 RTCritSectEnterDebug (&mCritSect,
225 "WriteLockHandle::lockWrite() return address >>>",
226 0, (RTUINTPTR) ASMReturnAddress());
227#else
228 RTCritSectEnter (&mCritSect);
229#endif
230 }
231
232 void unlockWrite()
233 {
234 RTCritSectLeave (&mCritSect);
235 }
236
237 void lockRead() { lockWrite(); }
238 void unlockRead() { unlockWrite(); }
239
240 uint32_t writeLockLevel() const
241 {
242 return RTCritSectGetRecursion (&mCritSect);
243 }
244
245 mutable RTCRITSECT mCritSect;
246};
247
248/**
249 * Lockable interface.
250 *
251 * This is an abstract base for classes that need read/write locking. Unlike
252 * RWLockHandle and other classes that makes the read/write semaphore a part of
253 * class data, this class allows subclasses to decide which semaphore handle to
254 * use.
255 */
256class Lockable
257{
258public:
259
260 /**
261 * Returns a pointer to a LockHandle used by AutoLock/AutoReaderLock for
262 * locking. Subclasses are allowed to return @c NULL -- in this case,
263 * the AutoLock/AutoReaderLock object constructed using an instance of
264 * such subclass will simply turn into no-op.
265 */
266 virtual LockHandle *lockHandle() const = 0;
267
268 /**
269 * Equivalent to <tt>#lockHandle()->isLockedOnCurrentThread()</tt>.
270 * Returns @c false if lockHandle() returns @c NULL.
271 */
272 bool isLockedOnCurrentThread()
273 {
274 LockHandle *h = lockHandle();
275 return h ? h->isLockedOnCurrentThread() : false;
276 }
277
278 /**
279 * Equivalent to <tt>#lockHandle()->rlock()</tt>.
280 * Returns @c NULL false if lockHandle() returns @c NULL.
281 */
282 LockOps *rlock()
283 {
284 LockHandle *h = lockHandle();
285 return h ? h->rlock() : NULL;
286 }
287
288 /**
289 * Equivalent to <tt>#lockHandle()->wlock()</tt>. Returns @c NULL false if
290 * lockHandle() returns @c NULL.
291 */
292 LockOps *wlock()
293 {
294 LockHandle *h = lockHandle();
295 return h ? h->wlock() : NULL;
296 }
297};
298
299/**
300 * Provides safe management of read/write semaphores in write mode.
301 *
302 * A read/write semaphore is represented by the LockHandle class. This semaphore
303 * can be requested ("locked") in two different modes: for reading and for
304 * writing. A write lock is exclusive and acts like a mutex: only one thread can
305 * acquire a write lock on the given semaphore at a time; all other threads
306 * trying to request a write lock or a read lock (see below) on the same
307 * semaphore will be indefinitely blocked until the owning thread releases the
308 * write lock.
309 *
310 * A read lock is shared. This means that several threads can acquire a read
311 * lock on the same semaphore at the same time provided that there is no thread
312 * that holds a write lock on that semaphore. Note that when there are one or
313 * more threads holding read locks, a request for a write lock on another thread
314 * will be indefinitely blocked until all threads holding read locks release
315 * them.
316 *
317 * Note that write locks can be nested -- the same thread can request a write
318 * lock on the same semaphore several times. In this case, the corresponding
319 * number of release calls must be done in order to completely release all
320 * nested write locks and make the semaphore available for locking by other
321 * threads.
322 *
323 * Read locks can be nested too in which case the same rule of the equal number
324 * of the release calls applies. Read locks can be also nested into write
325 * locks which means that the same thread can successfully request a read lock
326 * if it already holds a write lock. However, please note that the opposite is
327 * <b>not possible</b>: if a thread tries to request a write lock on the same
328 * semaphore it is already holding a read lock, it will definitely produce a
329 * <b>deadlock</b> (i.e. it will block forever waiting for itself).
330 *
331 * Note that instances of the AutoLock class manage write locks of read/write
332 * semaphores only. In order to manage read locks, please use the AutoReaderLock
333 * class.
334 *
335 * Safe semaphore management consists of the following:
336 * <ul>
337 * <li>When an instance of the AutoLock class is constructed given a valid
338 * semaphore handle, it will automatically request a write lock on that
339 * semaphore.
340 * </li>
341 * <li>When an instance of the AutoLock class constructed given a valid
342 * semaphore handle is destroyed (e.g. goes out of scope), it will
343 * automatically release the write lock that was requested upon construction
344 * and also all nested write locks requested later using the #lock() call
345 * (note that the latter is considered to be a program logic error, see the
346 * #~AutoLock() description for details).
347 * </li>
348 * </ul>
349 *
350 * Note that the LockHandle class taken by AutoLock constructors is an abstract
351 * base of the read/write semaphore. You should choose one of the existing
352 * subclasses of this abstract class or create your own subclass that implements
353 * necessary read and write lock semantics. The most suitable choice is the
354 * RWLockHandle class which provides full support for both read and write locks
355 * as describerd above. Alternatively, you can use the WriteLockHandle class if
356 * you only need write (exclusive) locking (WriteLockHandle requires less system
357 * resources and works faster).
358 *
359 * A typical usage pattern of the AutoLock class is as follows:
360 * <code>
361 * struct Struct : public RWLockHandle
362 * {
363 * ...
364 * };
365 *
366 * void foo (Struct &aStruct)
367 * {
368 * {
369 * // acquire a write lock of aStruct
370 * AutoLock alock (aStruct);
371 *
372 * // now we can modify aStruct in a thread-safe manner
373 * aStruct.foo = ...;
374 *
375 * // note that the write lock will be automatically released upon
376 * // execution of the return statement below
377 * if (!aStruct.bar)
378 * return;
379 *
380 * ...
381 * }
382 *
383 * // note that the write lock is automatically released here
384 * }
385 * </code>
386 *
387 * <b>Locking policy</b>
388 *
389 * When there are multiple threads and multiple objects to lock, there is always
390 * a potential possibility to produce a deadlock if the lock order is mixed up.
391 * Here is a classical example of a deadlock when two threads need to lock the
392 * same two objects in a row but do it in different order:
393 * <code>
394 * Thread 1:
395 * #1: AutoLock (mFoo);
396 * ...
397 * #2: AutoLock (mBar);
398 * ...
399 * Thread 2:
400 * #3: AutoLock (mBar);
401 * ...
402 * #4: AutoLock (mFoo);
403 * ...
404 * </code>
405 *
406 * If the threads happen to be scheduled so that #3 completes after #1 has
407 * completed but before #2 got control, the threads will hit a deadlock: Thread
408 * 2 will be holding mBar and waiting for mFoo at #4 forever because Thread 1 is
409 * holding mFoo and won't release it until it acquires mBar at #2 that will
410 * never happen because mBar is held by Thread 2.
411 *
412 * One of ways to avoid the described behavior is to never lock more than one
413 * obhect in a row. While it is definitely a good and safe practice, it's not
414 * always possible: the application logic may require several simultaneous locks
415 * in order to provide data integrity.
416 *
417 * One of the possibilities to solve the deadlock problem is to make sure that
418 * the locking order is always the same across the application. In the above
419 * example, it would mean that <b>both</b> threads should first requiest a lock
420 * of mFoo and then mBar (or vice versa). One of the methods to guarantee the
421 * locking order consistent is to introduce a set of locking rules. The
422 * advantage of this method is that it doesn't require any special semaphore
423 * implementation or additional control structures. The disadvantage is that
424 * it's the programmer who must make sure these rules are obeyed across the
425 * whole application so the human factor applies. Taking the simplicity of this
426 * method into account, it is chosen to solve potential deadlock problems when
427 * using AutoLock and AutoReaderLock classes. Here are the locking rules that
428 * must be obeyed by <b>all</b> users of these classes. Note that if more than
429 * one rule matches the given group of objects to lock, all of these rules must
430 * be met:
431 * <ol>
432 * <li>If there is a parent-child (or master-slave) relationship between the
433 * locked objects, parent (master) objects must be locked before child
434 * (slave) objects.
435 * </li>
436 * <li>When a group of equal objects (in terms of parent-child or
437 * master-slave relationsip) needs to be locked in a raw, the lock order
438 * must match the sort order (which must be consistent for the given group).
439 * </ol>
440 * Note that if there is no pragrammatically expressed sort order (e.g.
441 * the objects are not part of the sorted vector or list but instead are
442 * separate data members of a class), object class names sorted in alphabetical
443 * order must be used to determine the lock order. If there is more than one
444 * object of the given class, the object variable names' alphabetical order must
445 * be used as a lock order. When objects are not represented as individual
446 * variables, as in case of unsorted arrays/lists, the list of alphabetically
447 * sorted object UUIDs must be used to determine the sort order.
448 *
449 * All non-standard locking order must be avoided by all means, but when
450 * absolutely necessary, it must be clearly documented at relevant places so it
451 * is well seen by other developers. For example, if a set of instances of some
452 * class needs to be locked but these instances are not part of the sorted list
453 * and don't have UUIDs, then the class description must state what to use to
454 * determine the lock order (maybe some property that returns an unique value
455 * per every object).
456 */
457class AutoLock
458{
459public:
460
461 /**
462 * Constructs a null instance that does not manage any read/write
463 * semaphore.
464 *
465 * Note that all method calls on a null instance are no-ops. This allows to
466 * have the code where lock protection can be selected (or omitted) at
467 * runtime.
468 */
469 AutoLock() : mHandle (NULL), mLockLevel (0), mGlobalLockLevel (0) {}
470
471 /**
472 * Constructs a new instance that will start managing the given read/write
473 * semaphore by requesting a write lock.
474 */
475 AutoLock (LockHandle *aHandle)
476 : mHandle (aHandle), mLockLevel (0), mGlobalLockLevel (0)
477 { lock(); }
478
479 /**
480 * Constructs a new instance that will start managing the given read/write
481 * semaphore by requesting a write lock.
482 */
483 AutoLock (LockHandle &aHandle)
484 : mHandle (&aHandle), mLockLevel (0), mGlobalLockLevel (0)
485 { lock(); }
486
487 /**
488 * Constructs a new instance that will start managing the given read/write
489 * semaphore by requesting a write lock.
490 */
491 AutoLock (const Lockable &aLockable)
492 : mHandle (aLockable.lockHandle()), mLockLevel (0), mGlobalLockLevel (0)
493 { lock(); }
494
495 /**
496 * Constructs a new instance that will start managing the given read/write
497 * semaphore by requesting a write lock.
498 */
499 AutoLock (const Lockable *aLockable)
500 : mHandle (aLockable ? aLockable->lockHandle() : NULL)
501 , mLockLevel (0), mGlobalLockLevel (0)
502 { lock(); }
503
504 /**
505 * Release all write locks acquired by this instance through the #lock()
506 * call and destroys the instance.
507 *
508 * Note that if there there are nested #lock() calls without the
509 * corresponding number of #unlock() calls when the destructor is called, it
510 * will assert. This is because having an unbalanced number of nested locks
511 * is a program logic error which must be fixed.
512 */
513 ~AutoLock()
514 {
515 if (mHandle)
516 {
517 if (mGlobalLockLevel)
518 {
519 mGlobalLockLevel -= mLockLevel;
520 mLockLevel = 0;
521 for (; mGlobalLockLevel; -- mGlobalLockLevel)
522 mHandle->lockWrite();
523 }
524
525 AssertMsg (mLockLevel <= 1, ("Lock level > 1: %d\n", mLockLevel));
526 for (; mLockLevel; -- mLockLevel)
527 mHandle->unlockWrite();
528 }
529 }
530
531 /**
532 * Requests a write (exclusive) lock. If a write lock is already owned by
533 * this thread, increases the lock level (allowing for nested write locks on
534 * the same thread). Blocks indefinitely if a write lock or a read lock is
535 * already owned by another thread until that tread releases the locks,
536 * otherwise returns immediately.
537 */
538 void lock()
539 {
540 if (mHandle)
541 {
542 mHandle->lockWrite();
543 ++ mLockLevel;
544 Assert (mLockLevel != 0 /* overflow? */);
545 }
546 }
547
548 /**
549 * Decreases the write lock level increased by #lock(). If the level drops
550 * to zero (e.g. the number of nested #unlock() calls matches the number of
551 * nested #lock() calls), releases the lock making the managed semaphore
552 * available for locking by other threads.
553 */
554 void unlock()
555 {
556 if (mHandle)
557 {
558 AssertReturnVoid (mLockLevel != 0 /* unlock() w/o preceding lock()? */);
559 mHandle->unlockWrite();
560 -- mLockLevel;
561 }
562 }
563
564 /**
565 * Causes the current thread to completely release the write lock to make
566 * the managed semaphore immediately available for locking by other threads.
567 *
568 * This implies that all nested write locks on the semaphore will be
569 * released, even those that were acquired through the calls to #lock()
570 * methods of all other AutoLock/AutoReaderLock instances managing the
571 * <b>same</b> read/write semaphore.
572 *
573 * After calling this method, the only method you are allowed to call is
574 * #enter(). It will acquire the write lock again and restore the same
575 * level of nesting as it had before calling #leave().
576 *
577 * If this instance is destroyed without calling #enter(), the destructor
578 * will try to restore the write lock level that existed when #leave() was
579 * called minus the number of nested #lock() calls made on this instance
580 * itself. This is done to preserve lock levels of other
581 * AutoLock/AutoReaderLock instances managing the same semaphore (if any).
582 * Tiis also means that the destructor may indefinitely block if a write or
583 * a read lock is owned by some other thread by that time.
584 */
585 void leave()
586 {
587 if (mHandle)
588 {
589 AssertReturnVoid (mLockLevel != 0 /* leave() w/o preceding lock()? */);
590 AssertReturnVoid (mGlobalLockLevel == 0 /* second leave() in a row? */);
591
592 mGlobalLockLevel = mHandle->writeLockLevel();
593 AssertReturnVoid (mGlobalLockLevel >= mLockLevel /* logic error! */);
594
595 for (uint32_t left = mGlobalLockLevel; left; -- left)
596 mHandle->unlockWrite();
597 }
598 }
599
600 /**
601 * Causes the current thread to restore the write lock level after the
602 * #leave() call. This call will indefinitely block if another thread has
603 * successfully acquired a write or a read lock on the same semaphore in
604 * between.
605 */
606 void enter()
607 {
608 if (mHandle)
609 {
610 AssertReturnVoid (mLockLevel != 0 /* enter() w/o preceding lock()+leave()? */);
611 AssertReturnVoid (mGlobalLockLevel != 0 /* enter() w/o preceding leave()? */);
612
613 for (; mGlobalLockLevel; -- mGlobalLockLevel)
614 mHandle->lockWrite();
615 }
616 }
617
618 /** Returns @c true if this instance manages a null semaphore handle. */
619 bool isNull() const { return mHandle == NULL; }
620 bool operator !() const { return isNull(); }
621
622 /**
623 * Returns @c true if the current thread holds a write lock on the managed
624 * read/write semaphore. Returns @c false if the managed semaphore is @c
625 * NULL.
626 *
627 * @note Intended for debugging only.
628 */
629 bool isLockedOnCurrentThread() const
630 {
631 return mHandle ? mHandle->isLockedOnCurrentThread() : false;
632 }
633
634 /**
635 * Returns the current write lock level of the managed smaphore. The lock
636 * level determines the number of nested #lock() calls on the given
637 * semaphore handle. Returns @c 0 if the managed semaphore is @c
638 * NULL.
639 *
640 * Note that this call is valid only when the current thread owns a write
641 * lock on the given semaphore handle and will assert otherwise.
642 *
643 * @note Intended for debugging only.
644 */
645 uint32_t writeLockLevel() const
646 {
647 return mHandle ? mHandle->writeLockLevel() : 0;
648 }
649
650 /**
651 * Returns @c true if this instance manages the given semaphore handle.
652 *
653 * @note Intended for debugging only.
654 */
655 bool belongsTo (const LockHandle &aHandle) const { return mHandle == &aHandle; }
656
657 /**
658 * Returns @c true if this instance manages the given semaphore handle.
659 *
660 * @note Intended for debugging only.
661 */
662 bool belongsTo (const LockHandle *aHandle) const { return mHandle == aHandle; }
663
664 /**
665 * Returns @c true if this instance manages the given lockable object.
666 *
667 * @note Intended for debugging only.
668 */
669 bool belongsTo (const Lockable &aLockable)
670 {
671 return belongsTo (aLockable.lockHandle());
672 }
673
674 /**
675 * Returns @c true if this instance manages the given lockable object.
676 *
677 * @note Intended for debugging only.
678 */
679 bool belongsTo (const Lockable *aLockable)
680 {
681 return aLockable && belongsTo (aLockable->lockHandle());
682 }
683
684private:
685
686 DECLARE_CLS_COPY_CTOR_ASSIGN_NOOP (AutoLock)
687 DECLARE_CLS_NEW_DELETE_NOOP (AutoLock)
688
689 LockHandle *mHandle;
690 uint32_t mLockLevel;
691 uint32_t mGlobalLockLevel;
692
693 template <size_t> friend class AutoMultiWriteLockBase;
694};
695
696////////////////////////////////////////////////////////////////////////////////
697
698/**
699 * Provides safe management of read/write semaphores in read mode.
700 *
701 * This class differs from the AutoLock class is so that it's #lock() and
702 * #unlock() methods requests and release read (shared) locks on the managed
703 * read/write semaphore instead of write (exclusive) locks. See the AutoLock
704 * class description for more information about read and write locks.
705 *
706 * Safe semaphore management consists of the following:
707 * <ul>
708 * <li>When an instance of the AutoReaderLock class is constructed given a
709 * valid semaphore handle, it will automatically request a read lock on that
710 * semaphore.
711 * </li>
712 * <li>When an instance of the AutoReaderLock class constructed given a valid
713 * semaphore handle is destroyed (e.g. goes out of scope), it will
714 * automatically release the read lock that was requested upon construction
715 * and also all nested read locks requested later using the #lock() call (note
716 * that the latter is considered to be a program logic error, see the
717 * #~AutoReaderLock() description for details).
718 * </li>
719 * </ul>
720 *
721 * Note that the LockHandle class taken by AutoReaderLock constructors is an
722 * abstract base of the read/write semaphore. You should choose one of the
723 * existing subclasses of this abstract class or create your own subclass that
724 * implements necessary read and write lock semantics. The most suitable choice
725 * is the RWLockHandle class which provides full support for both read and write
726 * locks as describerd in AutoLock docs. Alternatively, you can use the
727 * WriteLockHandle class if you only need write (exclusive) locking
728 * (WriteLockHandle requires less system resources and works faster).
729 *
730 * However, please note that it absolutely does not make sense to manage
731 * WriteLockHandle semaphores with AutoReaderLock instances because
732 * AutoReaderLock instances will behave like AutoLock instances in this case
733 * since WriteLockHandle provides only exclusive write locking. You have been
734 * warned.
735
736 * A typical usage pattern of the AutoReaderLock class is as follows:
737 * <code>
738 * struct Struct : public RWLockHandle
739 * {
740 * ...
741 * };
742 *
743 * void foo (Struct &aStruct)
744 * {
745 * {
746 * // acquire a read lock of aStruct (note that two foo() calls may be
747 * executed on separate threads simultaneously w/o blocking each other)
748 * AutoReaderLock alock (aStruct);
749 *
750 * // now we can read aStruct in a thread-safe manner
751 * if (aStruct.foo)
752 * ...;
753 *
754 * // note that the read lock will be automatically released upon
755 * // execution of the return statement below
756 * if (!aStruct.bar)
757 * return;
758 *
759 * ...
760 * }
761 *
762 * // note that the read lock is automatically released here
763 * }
764 * </code>
765 */
766class AutoReaderLock
767{
768public:
769
770 /**
771 * Constructs a null instance that does not manage any read/write
772 * semaphore.
773 *
774 * Note that all method calls on a null instance are no-ops. This allows to
775 * have the code where lock protection can be selected (or omitted) at
776 * runtime.
777 */
778 AutoReaderLock() : mHandle (NULL), mLockLevel (0) {}
779
780 /**
781 * Constructs a new instance that will start managing the given read/write
782 * semaphore by requesting a read lock.
783 */
784 AutoReaderLock (LockHandle *aHandle)
785 : mHandle (aHandle), mLockLevel (0)
786 { lock(); }
787
788 /**
789 * Constructs a new instance that will start managing the given read/write
790 * semaphore by requesting a read lock.
791 */
792 AutoReaderLock (LockHandle &aHandle)
793 : mHandle (&aHandle), mLockLevel (0)
794 { lock(); }
795
796 /**
797 * Constructs a new instance that will start managing the given read/write
798 * semaphore by requesting a read lock.
799 */
800 AutoReaderLock (const Lockable &aLockable)
801 : mHandle (aLockable.lockHandle()), mLockLevel (0)
802 { lock(); }
803
804 /**
805 * Constructs a new instance that will start managing the given read/write
806 * semaphore by requesting a read lock.
807 */
808 AutoReaderLock (const Lockable *aLockable)
809 : mHandle (aLockable ? aLockable->lockHandle() : NULL)
810 , mLockLevel (0)
811 { lock(); }
812
813 /**
814 * Release all read locks acquired by this instance through the #lock()
815 * call and destroys the instance.
816 *
817 * Note that if there there are nested #lock() calls without the
818 * corresponding number of #unlock() calls when the destructor is called, it
819 * will assert. This is because having an unbalanced number of nested locks
820 * is a program logic error which must be fixed.
821 */
822 ~AutoReaderLock()
823 {
824 if (mHandle)
825 {
826 AssertMsg (mLockLevel <= 1, ("Lock level > 1: %d\n", mLockLevel));
827 for (; mLockLevel; -- mLockLevel)
828 mHandle->unlockRead();
829 }
830 }
831
832 /**
833 * Requests a read (shared) lock. If a read lock is already owned by
834 * this thread, increases the lock level (allowing for nested read locks on
835 * the same thread). Blocks indefinitely if a write lock is already owned by
836 * another thread until that tread releases the write lock, otherwise
837 * returns immediately.
838 *
839 * Note that this method returns immediately even if any number of other
840 * threads owns read locks on the same semaphore. Also returns immediately
841 * if a write lock on this semaphore is owned by the current thread which
842 * allows for read locks nested into write locks on the same thread.
843 */
844 void lock()
845 {
846 if (mHandle)
847 {
848 mHandle->lockRead();
849 ++ mLockLevel;
850 Assert (mLockLevel != 0 /* overflow? */);
851 }
852 }
853
854 /**
855 * Decreases the read lock level increased by #lock(). If the level drops to
856 * zero (e.g. the number of nested #unlock() calls matches the number of
857 * nested #lock() calls), releases the lock making the managed semaphore
858 * available for locking by other threads.
859 */
860 void unlock()
861 {
862 if (mHandle)
863 {
864 AssertReturnVoid (mLockLevel != 0 /* unlock() w/o preceding lock()? */);
865 mHandle->unlockRead();
866 -- mLockLevel;
867 }
868 }
869
870 /** Returns @c true if this instance manages a null semaphore handle. */
871 bool isNull() const { return mHandle == NULL; }
872 bool operator !() const { return isNull(); }
873
874 /**
875 * Returns @c true if this instance manages the given semaphore handle.
876 *
877 * @note Intended for debugging only.
878 */
879 bool belongsTo (const LockHandle &aHandle) const { return mHandle == &aHandle; }
880
881 /**
882 * Returns @c true if this instance manages the given semaphore handle.
883 *
884 * @note Intended for debugging only.
885 */
886 bool belongsTo (const LockHandle *aHandle) const { return mHandle == aHandle; }
887
888 /**
889 * Returns @c true if this instance manages the given lockable object.
890 *
891 * @note Intended for debugging only.
892 */
893 bool belongsTo (const Lockable &aLockable)
894 {
895 return belongsTo (aLockable.lockHandle());
896 }
897
898 /**
899 * Returns @c true if this instance manages the given lockable object.
900 *
901 * @note Intended for debugging only.
902 */
903 bool belongsTo (const Lockable *aLockable)
904 {
905 return aLockable && belongsTo (aLockable->lockHandle());
906 }
907
908private:
909
910 DECLARE_CLS_COPY_CTOR_ASSIGN_NOOP (AutoReaderLock)
911 DECLARE_CLS_NEW_DELETE_NOOP (AutoReaderLock)
912
913 LockHandle *mHandle;
914 uint32_t mLockLevel;
915};
916
917////////////////////////////////////////////////////////////////////////////////
918
919/**
920 * Helper template class for AutoMultiLockN classes.
921 *
922 * @param Cnt number of read/write semaphores to manage.
923 */
924template <size_t Cnt>
925class AutoMultiLockBase
926{
927public:
928
929 /**
930 * Releases all locks if not yet released by #unlock() and destroys the
931 * instance.
932 */
933 ~AutoMultiLockBase()
934 {
935 if (mIsLocked)
936 unlock();
937 }
938
939 /**
940 * Calls LockOps::lock() methods of all managed semaphore handles
941 * in order they were passed to the constructor.
942 *
943 * Note that as opposed to LockHandle::lock(), this call cannot be nested
944 * and will assert if so.
945 */
946 void lock()
947 {
948 AssertReturnVoid (!mIsLocked);
949
950 size_t i = 0;
951 while (i < ELEMENTS (mOps))
952 if (mOps [i])
953 mOps [i ++]->lock();
954 mIsLocked = true;
955 }
956
957 /**
958 * Calls LockOps::unlock() methods of all managed semaphore handles in
959 * reverse to the order they were passed to the constructor.
960 *
961 * Note that as opposed to LockHandle::unlock(), this call cannot be nested
962 * and will assert if so.
963 */
964 void unlock()
965 {
966 AssertReturnVoid (mIsLocked);
967
968 AssertReturnVoid (ELEMENTS (mOps) > 0);
969 size_t i = ELEMENTS (mOps);
970 do
971 if (mOps [-- i])
972 mOps [i]->unlock();
973 while (i != 0);
974 mIsLocked = false;
975 }
976
977protected:
978
979 AutoMultiLockBase() : mIsLocked (false) {}
980
981 LockOps *mOps [Cnt];
982 bool mIsLocked;
983
984private:
985
986 DECLARE_CLS_COPY_CTOR_ASSIGN_NOOP (AutoMultiLockBase)
987 DECLARE_CLS_NEW_DELETE_NOOP (AutoMultiLockBase)
988};
989
990/** AutoMultiLockBase <0> is meaningless and forbidden. */
991template<>
992class AutoMultiLockBase <0> { private : AutoMultiLockBase(); };
993
994/** AutoMultiLockBase <1> is meaningless and forbidden. */
995template<>
996class AutoMultiLockBase <1> { private : AutoMultiLockBase(); };
997
998////////////////////////////////////////////////////////////////////////////////
999
1000/* AutoMultiLockN class definitions */
1001
1002#define A(n) LockOps *l##n
1003#define B(n) mOps [n] = l##n
1004
1005/**
1006 * AutoMultiLock for 2 locks.
1007 *
1008 * The AutoMultiLockN family of classes provides a possibility to manage several
1009 * read/write semaphores at once. This is handy if all managed semaphores need
1010 * to be locked and unlocked synchronously and will also help to avoid locking
1011 * order errors.
1012 *
1013 * Instances of AutoMultiLockN classes are constructed from a list of LockOps
1014 * arguments. The AutoMultiLockBase::lock() method will make sure that the given
1015 * list of semaphores represented by LockOps pointers will be locked in order
1016 * they are passed to the constructor. The AutoMultiLockBase::unlock() method
1017 * will make sure that they will be unlocked in reverse order.
1018 *
1019 * The type of the lock to request is specified for each semaphore individually
1020 * using the corresponding LockOps getter of a LockHandle or Lockable object:
1021 * LockHandle::wlock() in order to request a write lock or LockHandle::rlock()
1022 * in order to request a read lock.
1023 *
1024 * Here is a typical usage pattern:
1025 * <code>
1026 * ...
1027 * LockHandle data1, data2;
1028 * ...
1029 * {
1030 * AutoMultiLock2 multiLock (data1.wlock(), data2.rlock());
1031 * // both locks are held here:
1032 * // - data1 is locked in write mode (like AutoLock)
1033 * // - data2 is locked in read mode (like AutoReaderLock)
1034 * }
1035 * // both locks are released here
1036 * </code>
1037 */
1038class AutoMultiLock2 : public AutoMultiLockBase <2>
1039{
1040public:
1041 AutoMultiLock2 (A(0), A(1))
1042 { B(0); B(1); lock(); }
1043};
1044
1045/** AutoMultiLock for 3 locks. See AutoMultiLock2 for more information. */
1046class AutoMultiLock3 : public AutoMultiLockBase <3>
1047{
1048public:
1049 AutoMultiLock3 (A(0), A(1), A(2))
1050 { B(0); B(1); B(2); lock(); }
1051};
1052
1053/** AutoMultiLock for 4 locks. See AutoMultiLock2 for more information. */
1054class AutoMultiLock4 : public AutoMultiLockBase <4>
1055{
1056public:
1057 AutoMultiLock4 (A(0), A(1), A(2), A(3))
1058 { B(0); B(1); B(2); B(3); lock(); }
1059};
1060
1061#undef B
1062#undef A
1063
1064////////////////////////////////////////////////////////////////////////////////
1065
1066/**
1067 * Helper template class for AutoMultiWriteLockN classes.
1068 *
1069 * @param Cnt number of write semaphores to manage.
1070 */
1071template <size_t Cnt>
1072class AutoMultiWriteLockBase
1073{
1074public:
1075
1076 /**
1077 * Calls AutoLock::lock() methods for all managed semaphore handles in order
1078 * they were passed to the constructor.
1079 */
1080 void lock()
1081 {
1082 size_t i = 0;
1083 while (i < ELEMENTS (mLocks))
1084 mLocks [i ++].lock();
1085 }
1086
1087 /**
1088 * Calls AutoLock::unlock() methods for all managed semaphore handles in
1089 * reverse to the order they were passed to the constructor.
1090 */
1091 void unlock()
1092 {
1093 AssertReturnVoid (ELEMENTS (mLocks) > 0);
1094 size_t i = ELEMENTS (mLocks);
1095 do
1096 mLocks [-- i].unlock();
1097 while (i != 0);
1098 }
1099
1100 /**
1101 * Calls AutoLock::leave() methods for all managed semaphore handles in
1102 * reverse to the order they were passed to the constructor.
1103 */
1104 void leave()
1105 {
1106 AssertReturnVoid (ELEMENTS (mLocks) > 0);
1107 size_t i = ELEMENTS (mLocks);
1108 do
1109 mLocks [-- i].leave();
1110 while (i != 0);
1111 }
1112
1113 /**
1114 * Calls AutoLock::enter() methods for all managed semaphore handles in order
1115 * they were passed to the constructor.
1116 */
1117 void enter()
1118 {
1119 size_t i = 0;
1120 while (i < ELEMENTS (mLocks))
1121 mLocks [i ++].enter();
1122 }
1123
1124protected:
1125
1126 AutoMultiWriteLockBase() {}
1127
1128 void setLockHandle (size_t aIdx, LockHandle *aHandle)
1129 { mLocks [aIdx].mHandle = aHandle; }
1130
1131private:
1132
1133 AutoLock mLocks [Cnt];
1134
1135 DECLARE_CLS_COPY_CTOR_ASSIGN_NOOP (AutoMultiWriteLockBase)
1136 DECLARE_CLS_NEW_DELETE_NOOP (AutoMultiWriteLockBase)
1137};
1138
1139/** AutoMultiWriteLockBase <0> is meaningless and forbidden. */
1140template<>
1141class AutoMultiWriteLockBase <0> { private : AutoMultiWriteLockBase(); };
1142
1143/** AutoMultiWriteLockBase <1> is meaningless and forbidden. */
1144template<>
1145class AutoMultiWriteLockBase <1> { private : AutoMultiWriteLockBase(); };
1146
1147////////////////////////////////////////////////////////////////////////////////
1148
1149/* AutoMultiLockN class definitions */
1150
1151#define A(n) LockHandle *l##n
1152#define B(n) setLockHandle (n, l##n)
1153
1154#define C(n) Lockable *l##n
1155#define D(n) setLockHandle (n, l##n ? l##n->lockHandle() : NULL)
1156
1157/**
1158 * AutoMultiWriteLock for 2 locks.
1159 *
1160 * The AutoMultiWriteLockN family of classes provides a possibility to manage
1161 * several read/write semaphores at once. This is handy if all managed
1162 * semaphores need to be locked and unlocked synchronously and will also help to
1163 * avoid locking order errors.
1164 *
1165 * The functionality of the AutoMultiWriteLockN class family is similar to the
1166 * functionality of the AutoMultiLockN class family (see the AutoMultiLock2
1167 * class for details) with two important differences:
1168 * <ol>
1169 * <li>Instances of AutoMultiWriteLockN classes are constructed from a list
1170 * of LockHandle or Lockable arguments directly instead of getting
1171 * intermediate LockOps interface pointers.
1172 * </li>
1173 * <li>All locks are requested in <b>write</b> mode.
1174 * </li>
1175 * <li>Since all locks are requested in write mode, bulk
1176 * AutoMultiWriteLockBase::leave() and AutoMultiWriteLockBase::enter()
1177 * operations are also available, that will leave and enter all managed
1178 * semaphores at once in the proper order (similarly to
1179 * AutoMultiWriteLockBase::lock() and AutoMultiWriteLockBase::unlock()).
1180 * </li>
1181 * </ol>
1182 *
1183 * Here is a typical usage pattern:
1184 * <code>
1185 * ...
1186 * LockHandle data1, data2;
1187 * ...
1188 * {
1189 * AutoMultiWriteLock2 multiLock (&data1, &data2);
1190 * // both locks are held in write mode here
1191 * }
1192 * // both locks are released here
1193 * </code>
1194 */
1195class AutoMultiWriteLock2 : public AutoMultiWriteLockBase <2>
1196{
1197public:
1198 AutoMultiWriteLock2 (A(0), A(1))
1199 { B(0); B(1); lock(); }
1200 AutoMultiWriteLock2 (C(0), C(1))
1201 { D(0); D(1); lock(); }
1202};
1203
1204/** AutoMultiWriteLock for 3 locks. See AutoMultiWriteLock2 for more details. */
1205class AutoMultiWriteLock3 : public AutoMultiWriteLockBase <3>
1206{
1207public:
1208 AutoMultiWriteLock3 (A(0), A(1), A(2))
1209 { B(0); B(1); B(2); lock(); }
1210 AutoMultiWriteLock3 (C(0), C(1), C(2))
1211 { D(0); D(1); D(2); lock(); }
1212};
1213
1214/** AutoMultiWriteLock for 4 locks. See AutoMultiWriteLock2 for more details. */
1215class AutoMultiWriteLock4 : public AutoMultiWriteLockBase <4>
1216{
1217public:
1218 AutoMultiWriteLock4 (A(0), A(1), A(2), A(3))
1219 { B(0); B(1); B(2); B(3); lock(); }
1220 AutoMultiWriteLock4 (C(0), C(1), C(2), C(3))
1221 { D(0); D(1); D(2); D(3); lock(); }
1222};
1223
1224#undef D
1225#undef C
1226#undef B
1227#undef A
1228
1229} /* namespace util */
1230
1231#endif // ____H_AUTOLOCK
1232
Note: See TracBrowser for help on using the repository browser.

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette