PDA

View Full Version : QThreads, QMutexes, and multiple access



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

wysota
12th January 2010, 03:32
It might be better to use QReadWriteLock instead of QMutex here.

coderbob
12th January 2010, 16:27
Than you for the response Wysota but I think there might be a mis interpretation of my questions.

QReadWriteLock are just simplified convince class for a QMutex and not needed in this situation. My Questions to be more to the point are if a variable is essentially a constant does it really need a lock when being read. Logic says no but I wanted to see if anyone had any wisdom in that area.

And the examples on QThread are very basic (which is fine I just needed more information) and was not sure if I should try to maintain global for QMutexes when it seemed more logical to just keep them inside the object and let the object control access to the data which felt more OOP.
The example uses a global QMutex since is just really a snippet and needed a way for the 2 classes to share a lock.

bob

wysota
12th January 2010, 16:39
In most cases read-only variables don't need to be protected. That's exactly what QReadWriteLock does - it lets many readers in but when a writer wants to step in, all readers and other writers become blocked.