The purpose of this is to prevent a re-entrant function call in a single thread, e.g. prevent the situation where func()
calls bar()
which calls func()
.
This is currently not used in any multithreaded code (and does not plan to be).
struct TranLock
{
static int count;
bool failed;
TranLock() { failed = count; if (!failed) ++count; }
~TranLock() { if (!failed) --count; }
};
int TranLock::count = 0;
Usage:
void func()
{
TranLock lock;
if ( lock.failed )
return; // or take other action
// the function's logic here
}
Is there a better idiom for this, e.g. involving std::shared_ptr
? C++11 features OK.
Update: As pointed out by Greg Hewgill, if multiple functions use TranLock
they will all have a shared lockout. Currently I only use it in one function, although it would be nice to see two different possible implementations:
- Lock which can be shared amongst functions
- Individual lock per function
(perhaps this could be controlled with a template parameter or something).