0

I remember seeing it in some conference, but can't find any information on this.

I want something like:

lock(_somelock)
{
    if (_someBool)
        return;

    DoStuff();
} // Implicit unlock

Instead of:

lock(_somelock);
if (_someBool)
{
    unlock(_somelock);
    return;
}

DoStuff();
unlock(_somelock);

As you can see the code gets very bloated with multiple early returns. Obviously one could make another function to handle locking/unlocking, but it's a lot nicer no?

Possible with C++11 standard library?

TheDespite
  • 333
  • 1
  • 2
  • 11

3 Answers3

6

Yes, you can use a std::lock_guard to wrap a mutex.

{
   std::lock_guard<std::mutex> lock(your_mutex);

    if (_someBool)
        return;

    DoStuff();

}
Marius Bancila
  • 16,053
  • 9
  • 49
  • 91
3

The standard idiom is to use a guard object whose lifetime encompasses the locked state of the mutex:

std::mutex m;
int shared_data;

// somewhere else

void foo()
{
    int x = compute_something();

    {
        std::lock_guard<std::mutex> guard(m);
        shared_data += x;
    }

    some_extra_work();
}
Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
0

You can simply create an autolock of your own.

Class AutoLock
{
  pthread_mutex_t *mpLockObj;

  AutoLock(pthread_mutex_t& mpLockObj)
  {
      mpLockObj = &mpLockObj;
      pthread_mutex_lock(mpLockObj);
  }

  ~AutoLock()
  {
     pthread_mutex_unlock(mpLockObj);
  }
};

use like:

#define LOCK(obj) AutoLock LocObj(obj);
int main()
{

  pthread_mutex_t lock;
  LOCK(lock);

  return 0; 
}
Yogesh
  • 565
  • 3
  • 21