Skip to content
  • 0 Votes
    2 Posts


    From experience:

    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.

    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.

    Mark the variable as volatile.

    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.