[Solved] QMutex for public static function in multi threaded application?
I have a class as below:
static QString name;
static QMutex *mutex;
static void getInt(QString *result, int opt);
void MyClass::getInt(QString *result, int opt)
mutex->lock();//is this required?
if(opt == 1)
*result = name + " one";
else if(opt == 2)
*result = name + " two";
So my question is that, is it required to use a QMutex for a public static const function if multiple threads may call it at the same time?
In other words, is it necessary to synchronise a function which has read only access to class variables?
- const modifier is wrong on static function.
- You probably should use mutex if different threads have access to same date.
Function that use only its parameters is thread-safe.
- At my point, you don't need to use mutex in you ex;
- You don'y modify the result param, so better type is "const QString &"
- pointer to QMutex is extra for me. I'd make it just an object.
If your function accesses shared data, you must protect if with a mutex. If it doesn't access shared data, then you don't have to. See http://qt-project.org/doc/qt-5/threads-synchronizing.html
Why do you use "QMutex*" instead of a "QMutex"?
- Thanks for your advice. I did not know that.
- In my case the threads have read only access to the class variables. Should I use QMutex?
- Updated the question, it was incorrect previously.
- I did for cache optimisation.
bq. If your function accesses shared data, you must protect it with a mutex.
While the doc you linked says
bq. When a piece of data is not being written to, it is safe for multiple threads to read from it simultaneously.
Is it not conflicting your statement.
BTW thanks for that link, it cleared many doubts that I had.
My last post was oversimplified. Please change "If your function ACCESSES shared data" to "If your function WRITES TO shared data" and "If your function READS shared data THAT MIGHT BE UPDATED".
If your function only reads the data, and the data never changes, then you don't have to lock a mutex.
Anyway, you're welcome; I'm glad to hear that you've learnt new things. Happy coding!