[Solved] QMutex for public static function in multi threaded application?



  • I have a class as below:

    @class MyClass
    {
    private:
    static QString name;
    static QMutex *mutex;
    public:
    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";
    mutex->unlock();
    }@

    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?



    1. const modifier is wrong on static function.
    2. You probably should use mutex if different threads have access to same date.
      Function that use only its parameters is thread-safe.
    3. At my point, you don't need to use mutex in you ex;
    4. You don'y modify the result param, so better type is "const QString &"
    5. pointer to QMutex is extra for me. I'd make it just an object.

  • Moderators

    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"?



  • @mapron

    1. Thanks for your advice. I did not know that.
    2. In my case the threads have read only access to the class variables. Should I use QMutex?
    3. Updated the question, it was incorrect previously.
    4. I did for cache optimisation.

    @JKSH

    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.


  • Moderators

    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!


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.