QMutex for Reading



  • Hi all,

    I have a question concerning the reading operation of a variable within a thread. MyThread inherits QThread.

    MyThread::startThread()
    {
        /* Thread not started, Mutex is not necessary */
        m_run = true;
        start();
    }
    
    MyThread::stopThread()
    {
        /* Thread started, Mutex is necessary (in case of other writing threads) */
        m_mutex.lock();
        m_run = false;
        m_mutex.unlock();
    }
    
    MyThread::run()
    {
        while( true )
        {
            /* do something here */
    
            /* Mutex necessary ?!? */
            if( !m_run )
                break;
         }
    }
    

    Is it necessary to use a mutex before the if statement in the while loop for thread safety while reading the variable m_run?
    Is it even necessary to use a mutex when a variable will only we written by one thread while other threads only read this variable?
    Is reading an atomic operation, even on multicore cpus?

    regards
    Oliver



  • @stvokr

    From experience:

    1. Your first assumption is incorrect:
      /* Thread not started, Mutex is not necessary */
      What if someone calls startThread() after the thread is started (it is not correct, but can and possibly will happen)... So fist check m_run before going on to start the thread.

    2. Make the intention clear: Either make m_run atomic using either Qt atomics or C++11 atomics or protect it with mutexes wherever it is used. Then you do not need to worry about the way that it is implemented on the specific compiler. If it is really timing critical code then you can start to worry about the additional overhead. From a maintainability and readability point of view it is then easy to know that the variable in question can be accessed from other threads. From my understanding reading is mostly atomic, thus you do not need the locking for the read.

    3. Mark the variable as volatile.

    [edit]
    To answer the second question:

    Is it even necessary to use a mutex when a variable will only we written by one thread while other threads only read this variable?

    If you can guarantee that this will always be the way that it will be used then it should be ok. So if you are the only one developing on the code, and that will use the code perhaps you can. But if you share the code or need to re-use some parts down the line (in a few years perhaps) you might not remember that there is such a limitation. Rather safe than sorry.

    I hope this helps a bit, someone else might have better insights.


Log in to reply
 

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