In a member function of a class running in a thread I want to protect access to some shared resources in an if-else ladder like following.
if (condition)
{}
// the mutex lock should be here
else if (specific condition)
// the mutex unlock should be here
{}
else ...
I wish to do locking in above manner because apart from accessing the shared resource for evaluating the specific condition
I do not access/use it anywhere and all the operations running every if/else block are pretty long running for which I do not want to block other thread from accessing that shared resource.
I am aware of scoped locks and mutexes but I cannot think of a way it can be used in this situation. Question is:
With mutex lock/unlock statement or even with a scoped lock how to achieve a lock/unlock on a specific condition in an if-else ladder?
Also I am looking to find this solution from C++ (03 perhaps) perspective (or for that matter not from languages like Java with implicit mutex support and synchronized blocks). Thanks in advance for all the help.
Wrap up the condition in a function that does the locking:
bool condition() {
mutex_lock();
bool result = ...
mutex_unlock();
return result;
}
then in the code just use
if () {
...
} else if (condition(...)) {
...
}
It should be work.
if (std::lock_guard{mutex_}, condition) {
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With