Does QMutex lock all the code between two lock call?
-
Suppouse I have this class
@
class Foo {
public:
int getValue(){
QMutexLocker(&mutex);
return this->value;
}public slots:
void updateValue(){
QMutexLocker(&mutex);
//doing stuff
this->value = someValue;
}private:
int value;
QMutex mutex;
}
@Am I sure that any possbile thread is waiting in getValue() while some other thread is running updateValue()?
-
Yup. Do you have some concerns about it?
One comment I have, although not necessarily applicable here, is that the "area" locked by mutex should be minimized e.g. if in your example "doing stuff" is some local computation that doesn't access any shared data then you could move it above the lock and only guard the final writing the result to the shared variable (value). Locking too much voids the benefits of multiple threads because locking a mutex is basically serializing execution and making threads wait.
-
It doesn't matter if it's a member or not. It would be the same if you had a global mutex. The important part is that the same mutex guards both regions.
Remember though that if you have a member mutex it will guard only access to that single instance of your object. If you want to separate calls to getValue and updateValue of any instance (e.g. when they use some shared globals or statics) then you need to use a global or static mutex, so that all access is guarded by the same one.