Yaniv G
Yaniv G

Reputation: 366

C++: Recursive locks - are there any drawbacks?

The background: I have a few threads that should access shared data. One of the threads might lock a Mutex, and within the mutual exclusion block, some functions (of the same thread) might call the very same lock again.

-I don't want to create many Mutexes

-I don't want to give up locking (obviously)

-I'd rather not change the design as it's quite a big change

void funcB()
{
   lock(MA);
   ...
   unlock(MA);
}

void funcA()
{
   lock(MA);
   ...
   funcB();
   ...
   unlock(MA);
}

It seems the only way to go is - use a recursive lock. Are there any drawbacks to using this feature?

Of course, if you think of any other way to solve this case, please share

Upvotes: 1

Views: 445

Answers (1)

Tony Delroy
Tony Delroy

Reputation: 106096

are there any drawbacks?

Slight performance penalty - measure if you care.

any other way to solve

You could give funcB a bool should_lock = true argument, or lots of variations on the theme, e.g. have one overload that locks a mutex then calls another overload that expects a reference to an already locked mutex (perhaps use an assert to check it's locked in debug builds): then funcA can call the latter.

Upvotes: 1

Related Questions