-3

Can any one helps me to understand how to lock variables in c++ in the most simple example, pretending I need to lock 2 variables in a function or a thread

Arwa196
  • 133
  • 1
  • 10

1 Answers1

4

Given:

int a;
int b;
std::mutex mutex;

Just do:

{
    std::lock_guard<decltype(mutex)> lock(mutex);
    ++a; // or whatever you wanna do to a
    b += a; // or whatever you wanna do to b
}

This will release the lock at the } automatically.

If you want to make sure that a lock is acquired before accessing the variables in question, you'll have to write a wrapper.

  • this will lock a and b for the { } scope,Right ? what if I don't need to lock all the variables in that scope ? – Arwa196 Nov 08 '14 at 11:53
  • No, it locks `mutex`. If you want to be sure the mutex is locked when accessing `a` and `b`, you'll have to write a wrapper as I mentioned in the answer. –  Nov 08 '14 at 11:54
  • You cannot lock arbitrary variables. You can only lock objects that have a `lock` method (see [`BasicLockable`](http://en.cppreference.com/w/cpp/concept/BasicLockable)). –  Nov 08 '14 at 11:54