coderbob
12th January 2010, 01:23
QMutex is used to lock access to a variable so multiple access from separate threads do not overwrite/read data at the same time it is possibly changing.
If I have an object that is shared between threads and they are only reading variables (that are constant and will never change) do I still need to lock them with a QMutex?
Second part of this is on code that is changing values can I pass around an object that self locks similar to something like:
class myDataObj : public QObject {
Q_OBJECT
public:
QMtuex var1locker;
QMutex var2locker;
qint32 readvar1();
void setvar1(int newvar1);
qint32 readvar2;
void setvar2(int newvar2);
private:
qint32 var1;
qint32 var2;
};
qint32 myDataObj::readvar1() {
qint32 return1;
var1locker.lock()
return1 = var1;
var1locker.unlock();
return return1;
}
void myDataObj::setvar1(int newvar1) {
var1locker.lock();
var1 = newvar1;
var1locker.unlock();
}
...
Is this a viable idea to wrap the QMutex in the object itself so I can just pass the object around to all the threads and have the object lock itself rather then having mutexes that have to be shared across all threads to control access?
Bob
If I have an object that is shared between threads and they are only reading variables (that are constant and will never change) do I still need to lock them with a QMutex?
Second part of this is on code that is changing values can I pass around an object that self locks similar to something like:
class myDataObj : public QObject {
Q_OBJECT
public:
QMtuex var1locker;
QMutex var2locker;
qint32 readvar1();
void setvar1(int newvar1);
qint32 readvar2;
void setvar2(int newvar2);
private:
qint32 var1;
qint32 var2;
};
qint32 myDataObj::readvar1() {
qint32 return1;
var1locker.lock()
return1 = var1;
var1locker.unlock();
return return1;
}
void myDataObj::setvar1(int newvar1) {
var1locker.lock();
var1 = newvar1;
var1locker.unlock();
}
...
Is this a viable idea to wrap the QMutex in the object itself so I can just pass the object around to all the threads and have the object lock itself rather then having mutexes that have to be shared across all threads to control access?
Bob