TheDespite
TheDespite

Reputation: 343

Mutex/Lock with scope/codeblock

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?

Upvotes: 0

Views: 425

Answers (3)

Yogesh
Yogesh

Reputation: 563

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; 
}

Upvotes: 0

Kerrek SB
Kerrek SB

Reputation: 476990

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();
}

Upvotes: 3

Marius Bancila
Marius Bancila

Reputation: 16318

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

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

    if (_someBool)
        return;

    DoStuff();

}

Upvotes: 6

Related Questions