Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C / C++ / MFC
  4. volatile local variable

volatile local variable

Scheduled Pinned Locked Moved C / C++ / MFC
data-structures
11 Posts 5 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • E Offline
    E Offline
    econy
    wrote on last edited by
    #1

    Hi, I read an old program, the programmer wrote some function like the following block, I am wonder if the volatile is necessary with a local variable. As I know, local variable is in stack, every time enter the function, local variable get a new stack address.

    void logRealClock(void)
    {
    volatile int second;
    volatile int minute;
    volatile int hour;

    second = globalDate->second;
    minute = globalDate->minute;
    hour = globalDate->hour;
    ....
    checkTime(second,minute,hour);
    ...
    globalRTC_REG.second = second;
    globalRTC_REG.minute = minute;
    globalRTC_REG.hour = hour;

    }

    D J 2 Replies Last reply
    0
    • E econy

      Hi, I read an old program, the programmer wrote some function like the following block, I am wonder if the volatile is necessary with a local variable. As I know, local variable is in stack, every time enter the function, local variable get a new stack address.

      void logRealClock(void)
      {
      volatile int second;
      volatile int minute;
      volatile int hour;

      second = globalDate->second;
      minute = globalDate->minute;
      hour = globalDate->hour;
      ....
      checkTime(second,minute,hour);
      ...
      globalRTC_REG.second = second;
      globalRTC_REG.minute = minute;
      globalRTC_REG.hour = hour;

      }

      D Offline
      D Offline
      David Knechtges
      wrote on last edited by
      #2

      The volatile keyword is used to force the compiler to not assume the variable's value. This is so that it does not optimize accesses away. http://en.wikipedia.org/wiki/Volatile_variable[^]

      E 1 Reply Last reply
      0
      • D David Knechtges

        The volatile keyword is used to force the compiler to not assume the variable's value. This is so that it does not optimize accesses away. http://en.wikipedia.org/wiki/Volatile_variable[^]

        E Offline
        E Offline
        econy
        wrote on last edited by
        #3

        Thanks,I read the Wiki article, but I still can't see the need of volatile for local variable. The example code only cause size of generated assembly code bigger, but useless.

        int main() {
        volatile int a = 10, b = 100, c = 0, d = 0;

        printf("%d", a + b);
        
        a = b;
        c = b;
        d = b;
        
        printf("%d", c + d);
        
        return 0;
        

        }

        P 1 Reply Last reply
        0
        • E econy

          Thanks,I read the Wiki article, but I still can't see the need of volatile for local variable. The example code only cause size of generated assembly code bigger, but useless.

          int main() {
          volatile int a = 10, b = 100, c = 0, d = 0;

          printf("%d", a + b);
          
          a = b;
          c = b;
          d = b;
          
          printf("%d", c + d);
          
          return 0;
          

          }

          P Offline
          P Offline
          pasztorpisti
          wrote on last edited by
          #4

          If you pass a pointer to your variable outside the function (for example to an interrupt handler) and then you guarantee the lifetime of that variable (for example by blocking on an event with this thread) and you want to use the variable in the function after finishing the block operation on the event then it could be useful (because the value of the variable might have been changed by other threads) but what I've described previously sounds quite pervert and awfully designed code. I don't think volatile local vars to be useful.

          E A 2 Replies Last reply
          0
          • P pasztorpisti

            If you pass a pointer to your variable outside the function (for example to an interrupt handler) and then you guarantee the lifetime of that variable (for example by blocking on an event with this thread) and you want to use the variable in the function after finishing the block operation on the event then it could be useful (because the value of the variable might have been changed by other threads) but what I've described previously sounds quite pervert and awfully designed code. I don't think volatile local vars to be useful.

            E Offline
            E Offline
            econy
            wrote on last edited by
            #5

            thanks, what you said like:

            volatile int* aPtr = aSharedMem;

            right? then in another thread,

            aSharedMem = aNewValue;

            then in the current thread, stalled before aSharedMem=aNewValue, then resume, *aPtr get the aNewValue. if local variable just copy a global's value, like: volatile int aLocal = aGlobal; then in another thread, aGlobal = aNewValue; in current thread, stalled before aGlobal = aNewValue, then resume, aLocal will get aNewValue?

            P 1 Reply Last reply
            0
            • P pasztorpisti

              If you pass a pointer to your variable outside the function (for example to an interrupt handler) and then you guarantee the lifetime of that variable (for example by blocking on an event with this thread) and you want to use the variable in the function after finishing the block operation on the event then it could be useful (because the value of the variable might have been changed by other threads) but what I've described previously sounds quite pervert and awfully designed code. I don't think volatile local vars to be useful.

              A Offline
              A Offline
              Aescleal
              wrote on last edited by
              #6

              It's not necessarily bad design to pass a reference to a local variable to another thread for processing. One example of where it might come in handy is splitting up an array into chunks and processing each chunk in separate threads. However using volatile as a synchronisation mechanism is not the sort of thing I'd recommend to try and avoid a proper synchronisation mechanism (i.e. a condition variable).

              P 1 Reply Last reply
              0
              • A Aescleal

                It's not necessarily bad design to pass a reference to a local variable to another thread for processing. One example of where it might come in handy is splitting up an array into chunks and processing each chunk in separate threads. However using volatile as a synchronisation mechanism is not the sort of thing I'd recommend to try and avoid a proper synchronisation mechanism (i.e. a condition variable).

                P Offline
                P Offline
                pasztorpisti
                wrote on last edited by
                #7

                Then we agree, in this case some kind of memory fence is used for synchronization that is usually built into the synch primitives like events. In this case you usually make a function call too to pass the job to another thread and usually this already prevents a compiler from optimizing away some things.

                1 Reply Last reply
                0
                • E econy

                  thanks, what you said like:

                  volatile int* aPtr = aSharedMem;

                  right? then in another thread,

                  aSharedMem = aNewValue;

                  then in the current thread, stalled before aSharedMem=aNewValue, then resume, *aPtr get the aNewValue. if local variable just copy a global's value, like: volatile int aLocal = aGlobal; then in another thread, aGlobal = aNewValue; in current thread, stalled before aGlobal = aNewValue, then resume, aLocal will get aNewValue?

                  P Offline
                  P Offline
                  pasztorpisti
                  wrote on last edited by
                  #8

                  // global scope. some other threads may use this pointer after its initialization...
                  int* globalptr;

                  void myfunc()
                  {
                  volatile int localvar = 0;
                  globalptr = &localvar;
                  //blah blah
                  //wait for something

                  // start using the volatile var again:
                  printf("localvar: %d\\n", localvar);
                  // In this case the compiler is forced to read up the value of
                  // localvar again from memory even if it would be present in a register.
                  // Maybe the compiler is smart enough to figure out that forming a pointer
                  // to the local var is suspicious but even if you hide this from the compiler
                  // with some ugly magic it will read the value from the memory when it comes
                  // to printing/using it without doing any optimizations/caching.
                  

                  }

                  E 1 Reply Last reply
                  0
                  • P pasztorpisti

                    // global scope. some other threads may use this pointer after its initialization...
                    int* globalptr;

                    void myfunc()
                    {
                    volatile int localvar = 0;
                    globalptr = &localvar;
                    //blah blah
                    //wait for something

                    // start using the volatile var again:
                    printf("localvar: %d\\n", localvar);
                    // In this case the compiler is forced to read up the value of
                    // localvar again from memory even if it would be present in a register.
                    // Maybe the compiler is smart enough to figure out that forming a pointer
                    // to the local var is suspicious but even if you hide this from the compiler
                    // with some ugly magic it will read the value from the memory when it comes
                    // to printing/using it without doing any optimizations/caching.
                    

                    }

                    E Offline
                    E Offline
                    econy
                    wrote on last edited by
                    #9

                    is the following scenario, the volatile is useful?

                    //global scope
                    int globalVar;

                    //in task1
                    void task1SetGlobal(void)
                    {

                    if (xyz == 100)
                    globalPtr = 100;
                    }

                    ...
                    //in task2
                    void task2GetGlobal(void)
                    {
                    volatile int localVar = 0;

                    localVar = globalVar;

                    if (localVar < 100 ) doSth;
                    else if (localVar == 100) do100Thing;

                    }

                    P 1 Reply Last reply
                    0
                    • E econy

                      is the following scenario, the volatile is useful?

                      //global scope
                      int globalVar;

                      //in task1
                      void task1SetGlobal(void)
                      {

                      if (xyz == 100)
                      globalPtr = 100;
                      }

                      ...
                      //in task2
                      void task2GetGlobal(void)
                      {
                      volatile int localVar = 0;

                      localVar = globalVar;

                      if (localVar < 100 ) doSth;
                      else if (localVar == 100) do100Thing;

                      }

                      P Offline
                      P Offline
                      pasztorpisti
                      wrote on last edited by
                      #10

                      Not really. In order to understand volatile you should first understand some other concepts like multithreading and caching and all the related problems that can cause problems along with the optimizations done by the compiler.

                      1 Reply Last reply
                      0
                      • E econy

                        Hi, I read an old program, the programmer wrote some function like the following block, I am wonder if the volatile is necessary with a local variable. As I know, local variable is in stack, every time enter the function, local variable get a new stack address.

                        void logRealClock(void)
                        {
                        volatile int second;
                        volatile int minute;
                        volatile int hour;

                        second = globalDate->second;
                        minute = globalDate->minute;
                        hour = globalDate->hour;
                        ....
                        checkTime(second,minute,hour);
                        ...
                        globalRTC_REG.second = second;
                        globalRTC_REG.minute = minute;
                        globalRTC_REG.hour = hour;

                        }

                        J Offline
                        J Offline
                        jschell
                        wrote on last edited by
                        #11

                        Probably just me but given the code that was posted I can't see any reason for volatile.

                        1 Reply Last reply
                        0
                        Reply
                        • Reply as topic
                        Log in to reply
                        • Oldest to Newest
                        • Newest to Oldest
                        • Most Votes


                        • Login

                        • Don't have an account? Register

                        • Login or register to search.
                        • First post
                          Last post
                        0
                        • Categories
                        • Recent
                        • Tags
                        • Popular
                        • World
                        • Users
                        • Groups