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
Asked
Active
Viewed 2,052 times
-3
-
3You mean like this: http://en.cppreference.com/w/cpp/thread/lock_guard? – Mike Seymour Nov 08 '14 at 11:46
-
You mean a mutually exclusive lock like `std::mutex`? – PeterT Nov 08 '14 at 11:46
-
2example in cppreference is more than enough, it's quite simple. – oblitum Nov 08 '14 at 11:48
-
Can I lock a variable of type int ? – Arwa196 Nov 08 '14 at 11:49
-
1@Arwa196 _"Can I lock a variable of type int ?"_ Did you actually read the sample there? – πάντα ῥεῖ Nov 08 '14 at 11:51
-
No, you don't lock just any variable, the lock itself is a variable you use in order to ensure you have ownership of some critical section – Leeor Nov 08 '14 at 11:51
1 Answers
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