Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to put mutex lock & unlock for a specific condition in if-else ladder?

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.

like image 376
Chadwick Robbert Avatar asked Jun 28 '15 21:06

Chadwick Robbert


2 Answers

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(...)) {
...
}
like image 60
6502 Avatar answered Oct 22 '22 08:10

6502


It should be work.

if (std::lock_guard{mutex_}, condition) {
...
}
like image 1
Faker Avatar answered Oct 22 '22 08:10

Faker