Thread: To Volatile, or not to Volatile?

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #8
    Registered User
    Join Date
    Oct 2008
    Posts
    1,262
    Quote Originally Posted by phantomotap View Post
    You say you are protecting reads and writes to `isRunning_' (Curse you for making me type '_' at the end!) with a "mutex". If that "mutex" is a full mutually exclusive lock the variable `isRunning_' does not need to be `volatile' in the context you've used it in the original post. The lock protects writes from the great "elsewhere" while reading so can't be updated beyond that scope so the cached value may be safely assumed to be correct.
    I guess I didn't understand volatile as well as I thought, then (sorry for my confusion). The code more accurately looks like this (should've written this in the first place):
    Code:
    class SomeClass {
      public:
        SomeClass()
        : isRunning(true)
        {
            createThread();
        }
     
        ~SomeClass()
        {
            pthread_mutex_lock(...);
            isRunning = false;
            pthread_mutex_unlock(...);
            waitForThread();
        }
     
      protected:
        void threadFunction()
        {
            while(1) {
                pthread_mutex_lock(...);
                if(!isRunning)
                    break;
    
                pthread_mutex_unlock(...);
    
                ...
            }
        }
     
        ...
     
      private:
        [volatile??] bool isRunning;
    };
    (I know, I'm not unlocking the mutex, again, laziness, but I did remove the underscore for you ;-).

    However, I don't see how that would make a difference. As I understood it, the compiler could still recognize that the isRunning variable is not modified in the function and thus must always remain the same, allowing it to cache the value, or store it in a register, rather than reading it from memory every time it's accessed.

    So what's the error in my logic, or my understanding of volatile?

    Thanks!

    Evoex
    Last edited by EVOEx; 05-11-2012 at 12:44 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Const and volatile
    By GokhanK in forum C Programming
    Replies: 9
    Last Post: 01-16-2011, 06:55 PM
  2. Volatile Variables
    By Gauravmore in forum C Programming
    Replies: 4
    Last Post: 01-11-2011, 08:29 AM
  3. what are the implications of volatile....
    By sanddune008 in forum C Programming
    Replies: 6
    Last Post: 06-29-2010, 04:33 AM
  4. volatile??
    By jacktibet in forum C Programming
    Replies: 2
    Last Post: 05-29-2003, 03:46 PM
  5. volatile keyword help!!!!
    By penney in forum Linux Programming
    Replies: 2
    Last Post: 03-12-2003, 08:09 AM