PCL
|
Automatic reentrancy guard sentinel. More...
#include <Atomic.h>
Public Member Functions | |
AutoReentrancyGuard (AtomicInt &guard) | |
~AutoReentrancyGuard () | |
operator bool () const volatile | |
AutoReentrancyGuard allows you to protect a block of code ensuring that it cannot be reentrant. All you need is a static AtomicInt variable that works as a 'busy state' flag persistent across function invocations.
Consider the following example:
The function foo
is not reentrant, so we want to protect it against possible reentrant invocations while the function's code is being executed.
The flag
variable is initially zero (because AtomicInt's default constructor initializes its integer member to zero). The first time foo
is called, AutoReentrancyGuard's constructor can change the value of flag
from zero to one as an atomic operation. When this happens, AutoReentrancyGuard::operator bool() returns true, and the code protected within the if
block can be executed.
When the guard
object gets out of scope (just before the foo
function returns), its class destructor resets flag
to zero automatically, which permits the next non-reentrant execution of foo
. However, if foo
is called again before guard
is destroyed, a newly constructed AutoReentrancyGuard object cannot make a transition 0 -> 1 with the static flag
variable, and hence a reentrant execution of the protected code is not allowed (in this case, the function simply does nothing and returns after the if
block). Note that the protected code can freely return from the function or throw exceptions; the flag
variable will be reset to zero automatically when guard
gets out of scope.
Since AutoReentrancyGuard uses AtomicInt to implement atomic transitions, code blocks can be protected against reentrant execution in multithreaded environments.
The macros PCL_REENTRANCY_GUARDED_BEGIN and PCL_REENTRANCY_GUARDED_END greatly simplify reentrancy protection. For example, the above code could be implemented as follows:
In addition, the macros PCL_CLASS_REENTRANCY_GUARD and PCL_CLASS_REENTRANCY_GUARDED_BEGIN are useful for protection of all non-reentrant member functions of a class, and the macros PCL_MEMBER_REENTRANCY_GUARD and PCL_MEMBER_REENTRANCY_GUARDED_BEGIN provide protection of specific member functions. See these macros for examples.
|
inline |
Constructs an AutoReentrancyGuard object to monitor the specified guard variable. If guard
is zero, its value is set to one as an atomic operation. If guard
is nonzero, its value is not changed.
Definition at line 465 of file Atomic.h.
References pcl::AtomicInt::TestAndSet().
|
inline |
Destroys this object. If the value of the monitored guard variable (see the class constructor) was zero when this object was constructed, its value is reset to zero as an atomic operation.
Definition at line 476 of file Atomic.h.
References pcl::AtomicInt::Store().
|
inline |