BDE 4.14.0 Production release
|
Provide a mutex capable of keeping track of wait and hold time.
This component provides a class, bslmt::MeteredMutex
, that functions as a mutex and has additional capability to keep track of wait time and hold time. This class can be used, for example, in evaluating the performance of an application, based on its lock contention behavior.
Wait time is defined as the sum of the time intervals between each call to lock
(or tryLock
) on the underlying mutex and the return of that call. Note that if one or more threads are waiting for the lock at the point when waitTime
is called, those waiting time intervals are not included in the returned wait time. Hold time is defined as the sum of the time intervals between return from each call to lock
(or a successful call to tryLock
) on the underlying mutex and the subsequent call to unlock
. Note that if a thread is holding the lock at the point when holdTime
is called, then that holding time is not included in the returned hold time.
It should be noted that the overhead in keeping track of wait and hold time is very small. We do not use additional mutexes to manipulate these times, instead, we use atomic data types (which have very small overhead compared to a mutex) to update these times atomically.
Times reported by waitTime
and holdTime
are (close) approximate times and not 100% accurate. This inaccuracy can sometime cause surprising behavior. For example, one can incorrectly assume lock()
and while (tryLock() != 0);
to be effectively the same (both disallowing the thread to advance until the lock is acquired) but the wait time reported in the first case can be much more accurate than that of the second because the lock
is called only once (and thus computation error is introduced only once) in the first case.
This section illustrates intended use of this component.
In the following example, we have NUM_THREADS
threads (that are sequentially numbered from 0
to NUM_THREADS-1
) and two counters evenCount
and oddCount
. evenCount
is incremented by the even numbered threads and oddCount
is incremented by the odd ones. We considers two strategies to increment these counters. In the first strategy (strategy1), we use two mutexes (one for each counter) and in the second strategy (strategy2), we use a single mutex for both counters.
Then in the application main
:
We measured the wait times for each strategy. Intuitively, the wait time for the second strategy should be greater than that of the first. The output was consistent with our expectation.