how to use volatile key word?

Discussion in 'C++' started by ä¼è™Ž, Jun 26, 2012.

  1. ä¼è™Ž

    ä¼è™Ž Guest

    how to use volatile key word?

    Assume I have a global variable shared by two or more tasks. Do I need to declare it as volatile?

    When will a non-volatile global variable be written back to memory from a register copy? Before a function call? Or before the return statement?
    ä¼è™Ž, Jun 26, 2012
    #1
    1. Advertising

  2. On 6/26/2012 12:11 PM, ä¼è™Ž wrote:
    > how to use volatile key word?
    >
    > Assume I have a global variable shared by two or more tasks. Do I
    > need to declare it as volatile?


    'volatile' usually means that the object's value can be changed at any
    moment by some mechanism outside of your program control. When you have
    a global variable shared between parts of *your program*, that's all
    under your control, and hence doesn't need to be declared 'volatile'.

    > When will a non-volatile global variable be written back to memory
    > from a register copy? Before a function call? Or before the return
    > statement?


    Side effects (like changing memory) happen at "sequence points", within
    the same thread. Shared [between threads] data need to be protected
    better, and there are mechanisms for that - see "atomic operations" and
    "synchronization". That's all in theory, of course. Do you have a
    particular problem?

    V
    --
    I do not respond to top-posted replies, please don't ask
    Victor Bazarov, Jun 26, 2012
    #2
    1. Advertising

  3. Paavo Helde <> wrote:
    > Volatile is meant to be used for accessing memory-mapped hardware, if you
    > are not writing device drivers or such you can just forget about it. It is
    > neither needed nor sufficient for portable thread synchronisation.


    'volatile' might not be sufficient for thread synchronization nor atomicity,
    but it can certainly make a difference in a multithreaded program.

    In a program I had a case where I was just reading an integral from one
    thread that was changed by another thread to signal a minor, unimportant
    effect (namely something related to updating the UI). This did not require
    full-fledged locking (which would have made it needlessly expensive) because
    if the integral had a wrong value for a split second, that wasn't really
    a catastrophical event.

    However, 'volatile' had a major impact on that integral. Without it, the
    other thread was not seeing the changes immediately, causing a noticeable
    delay (it was a situation where the thread that was setting that integral
    did it inside a loop, and the compiler was optimizing the updating of the
    variable in such a way that the actual writing to the extern variable was
    delayed to be after the loop). With 'volatile' the variable was always
    updated immediately.
    Juha Nieminen, Jun 27, 2012
    #3
  4. ä¼è™Ž

    Mark Guest

    On Tue, 26 Jun 2012 13:53:23 -0500, Paavo Helde
    <> wrote:

    >=?UTF-8?B?5LyP6JmO?= <> wrote in
    >news::
    >
    >> how to use volatile key word?

    >
    >Volatile is meant to be used for accessing memory-mapped hardware, if you
    >are not writing device drivers or such you can just forget about it. It is
    >neither needed nor sufficient for portable thread synchronisation.


    I'd say the volatile keywork is not sufficient but it is necessary in
    some circumstances.

    >See e.g. http://en.wikipedia.org/wiki/Volatile_variable


    This page does show cases where use of the volatile keyword is
    necessary.
    --
    (\__/) M.
    (='.'=) If a man stands in a forest and no woman is around
    (")_(") is he still wrong?
    Mark, Jun 27, 2012
    #4
  5. ä¼è™Ž

    Ian Collins Guest

    On 06/27/12 05:32 PM, Juha Nieminen wrote:
    > Paavo Helde<> wrote:
    >> Volatile is meant to be used for accessing memory-mapped hardware, if you
    >> are not writing device drivers or such you can just forget about it. It is
    >> neither needed nor sufficient for portable thread synchronisation.

    >
    > 'volatile' might not be sufficient for thread synchronization nor atomicity,
    > but it can certainly make a difference in a multithreaded program.
    >
    > In a program I had a case where I was just reading an integral from one
    > thread that was changed by another thread to signal a minor, unimportant
    > effect (namely something related to updating the UI). This did not require
    > full-fledged locking (which would have made it needlessly expensive) because
    > if the integral had a wrong value for a split second, that wasn't really
    > a catastrophical event.


    Did you measure? In the absence of contention, the impact of locking
    should be close to none.

    --
    Ian Collins
    Ian Collins, Jun 27, 2012
    #5
  6. Paavo Helde <> wrote:
    > Juha Nieminen <> wrote in
    >> In a program I had a case where I was just reading an integral from
    >> one thread that was changed by another thread to signal a minor,
    >> unimportant effect (namely something related to updating the UI). This
    >> did not require full-fledged locking (which would have made it
    >> needlessly expensive) because if the integral had a wrong value for a
    >> split second, that wasn't really a catastrophical event.

    >
    > Out of curiosity - did you measure how much the "needlessly expensive"
    > locking was slower than using a volatile? I'm asking because I find myself
    > often in urge to invent all kind of clever tricks to bypass proper locking.


    No, but it was enough that the options were between writing 'volatile'
    and several lines of code using a non-standard library to implement proper
    locking, so the choice was rather clear to me.

    (In C++11 it might have been enough to declare the integral to be atomic,
    and it would probably have been equally fast and fully synchronized. However,
    I did not have C++11 at my disposal at that time.)
    Juha Nieminen, Jun 28, 2012
    #6
  7. Ian Collins <> wrote:
    > Did you measure? In the absence of contention, the impact of locking
    > should be close to none.


    Locking is always expensive, even if no thread has to wait at any point.

    That's the very reason why so much research is being done on lock-free
    containers and atomic operations.

    Anyways, if the choice is between writing 'volatile' and writing several
    lines of code to implement locking in a situation where locking is not
    needed, the choice is pretty clear.
    Juha Nieminen, Jun 28, 2012
    #7
  8. ä¼è™Ž

    Ian Collins Guest

    On 06/28/12 05:55 PM, Juha Nieminen wrote:
    > Ian Collins<> wrote:
    >> Did you measure? In the absence of contention, the impact of locking
    >> should be close to none.

    >
    > Locking is always expensive, even if no thread has to wait at any point.
    >
    > That's the very reason why so much research is being done on lock-free
    > containers and atomic operations.
    >
    > Anyways, if the choice is between writing 'volatile' and writing several
    > lines of code to implement locking in a situation where locking is not
    > needed, the choice is pretty clear.


    Until you have to run on a multi-core system....

    --
    Ian Collins
    Ian Collins, Jun 28, 2012
    #8
  9. ä¼è™Ž

    Mark Guest

    On Wed, 27 Jun 2012 16:12:05 -0500, Paavo Helde
    <> wrote:

    >Mark <> wrote in
    >news::
    >
    >>
    >>>See e.g. http://en.wikipedia.org/wiki/Volatile_variable

    >>
    >> This page does show cases where use of the volatile keyword is
    >> necessary.

    >
    >Not sure what you mean, for C and C++ I see only discussion about memory-
    >mapped hardware. The examples about multi-thread synchronization with
    >volatile are talking about Java and C# where this keyword apparently means
    >something different.


    As I understand it there is still a risk of the unsafe opimizations
    which the volatile keyword would prevent.
    --
    (\__/) M.
    (='.'=) If a man stands in a forest and no woman is around
    (")_(") is he still wrong?
    Mark, Jun 28, 2012
    #9
  10. Ian Collins <> wrote:
    >> Anyways, if the choice is between writing 'volatile' and writing several
    >> lines of code to implement locking in a situation where locking is not
    >> needed, the choice is pretty clear.

    >
    > Until you have to run on a multi-core system....


    What difference would that make?
    Juha Nieminen, Jun 28, 2012
    #10
  11. ä¼è™Ž

    Luca Risolia Guest

    On 28/06/2012 07:55, Juha Nieminen wrote:
    > Locking is always expensive, even if no thread has to wait at any point.
    >
    > That's the very reason why so much research is being done on lock-free
    > containers and atomic operations.


    Globally speaking, with regard to the C++11 standard, atomic types may
    use non-blocking locks in the implementation. The only exception is
    std::atomic_flag, which is guaranteed not to use locks. This means that
    lock-free data structures and are not necessarily wait-free data structures.

    Writing wait-free data structures is extremely hard and even when you
    get them right, you should make sure that the benefit outweighs the
    cost, since the group of atomic operations used to implement them can be
    much slower than non-atomic counterpart. In other words, the main reason
    to write lock-free and wait-free code is to increase the potential for
    concurrency, but it may well decrease overall performance.

    For these reasons it's important to identify the relevant performance
    aspect and profile various alternatives on the target platforms before
    deciding.
    Luca Risolia, Jun 28, 2012
    #11
  12. Mark wrote:

    > On Wed, 27 Jun 2012 16:12:05 -0500, Paavo Helde
    > <> wrote:
    >
    >>Mark <> wrote in
    >>news::
    >>
    >>>
    >>>>See e.g. http://en.wikipedia.org/wiki/Volatile_variable
    >>>
    >>> This page does show cases where use of the volatile keyword is
    >>> necessary.

    >>
    >> Not sure what you mean, for C and C++ I see only discussion about
    >> memory- mapped hardware. The examples about multi-thread
    >> synchronization with volatile are talking about Java and C# where
    >> this keyword apparently means something different.

    >
    > As I understand it there is still a risk of the unsafe opimizations
    > which the volatile keyword would prevent.


    While that's true, the memory barriers that come with synchronized
    processor instructions, synchronization library functions/objects or the
    new C++ synchronization mechanisms prevent these unsafe optimizations
    also. That's why volatile is not necessary if you use these.

    Gerhard
    Gerhard Fiedler, Jun 28, 2012
    #12
  13. ä¼è™Ž

    Ian Collins Guest

    On 06/28/12 08:46 PM, Juha Nieminen wrote:
    > Ian Collins<> wrote:
    >>> Anyways, if the choice is between writing 'volatile' and writing several
    >>> lines of code to implement locking in a situation where locking is not
    >>> needed, the choice is pretty clear.

    >>
    >> Until you have to run on a multi-core system....

    >
    > What difference would that make?


    On reflection, possibly not a lot. volatile should keep the variable
    out of caches and visible to the other cores.

    --
    Ian Collins
    Ian Collins, Jun 28, 2012
    #13
  14. ä¼è™Ž

    Dombo Guest

    Op 28-Jun-12 7:55, Juha Nieminen schreef:
    > Ian Collins<> wrote:
    >> Did you measure? In the absence of contention, the impact of locking
    >> should be close to none.

    >
    > Locking is always expensive, even if no thread has to wait at any point.


    It depends; for example on Windows critical sections have minimal
    overhead on single core systems when there is no thread contention.
    Basically it boils down to a (sort-of) atomic test-and-set instruction,
    and only when the test fails it makes the (expensive) jump to kernel
    mode to halt the thread. On multi-core systems the test-and-set
    instruction gets a LOCK prefix to synchronize across cores which makes
    it a bit more expensive. OTOH if you use just 'volatile' variables to
    synchronize across threads in on x86 multi-core environments you would
    need the LOCK prefix as well for read-modify-write operations.

    > That's the very reason why so much research is being done on lock-free
    > containers and atomic operations.
    >
    > Anyways, if the choice is between writing 'volatile' and writing several
    > lines of code to implement locking in a situation where locking is not
    > needed, the choice is pretty clear.


    In that case you might even get away with leaving out 'volatile' as well.
    Dombo, Jun 28, 2012
    #14
  15. ä¼è™Ž

    Dombo Guest

    Op 28-Jun-12 21:16, Ian Collins schreef:
    > On 06/28/12 08:46 PM, Juha Nieminen wrote:
    >> Ian Collins<> wrote:
    >>>> Anyways, if the choice is between writing 'volatile' and writing
    >>>> several
    >>>> lines of code to implement locking in a situation where locking is not
    >>>> needed, the choice is pretty clear.
    >>>
    >>> Until you have to run on a multi-core system....

    >>
    >> What difference would that make?

    >
    > On reflection, possibly not a lot. volatile should keep the variable out
    > of caches and visible to the other cores.


    I don't know what the C++ 11 standard says about this but, on VS2010 it
    does nothing special to keep volatile variables out of the cache.
    Dombo, Jun 28, 2012
    #15
  16. Juha Nieminenæ–¼ 2012å¹´6月28日星期四UTC+8下åˆ1時53分40秒寫é“:
    > Paavo Helde <> wrote:
    > > Juha Nieminen <> wrote in
    > >> In a program I had a case where I was just reading an integral from
    > >> one thread that was changed by another thread to signal a minor,


    Well, this is the old joke of C with switches and cases not dupliating
    the key value in cores to execute in parallel.



    > >> unimportant effect (namely something related to updating the UI). This
    > >> did not require full-fledged locking (which would have made it
    > >> needlessly expensive) because if the integral had a wrong value for a
    > >> split second, that wasn't really a catastrophical event.

    > >
    > > Out of curiosity - did you measure how much the "needlessly expensive"
    > > locking was slower than using a volatile? I'm asking because I find myself
    > > often in urge to invent all kind of clever tricks to bypass proper locking.

    >
    > No, but it was enough that the options were between writing 'volatile'
    > and several lines of code using a non-standard library to implement proper
    > locking, so the choice was rather clear to me.
    >
    > (In C++11 it might have been enough to declare the integral to be atomic,
    > and it would probably have been equally fast and fully synchronized. However,
    > I did not have C++11 at my disposal at that time.)




    Juha Nieminenæ–¼ 2012å¹´6月28日星期四UTC+8下åˆ1時53分40秒寫é“:
    > Paavo Helde <> wrote:
    > > Juha Nieminen <> wrote in
    > >> In a program I had a case where I was just reading an integral from
    > >> one thread that was changed by another thread to signal a minor,
    > >> unimportant effect (namely something related to updating the UI). This
    > >> did not require full-fledged locking (which would have made it
    > >> needlessly expensive) because if the integral had a wrong value for a
    > >> split second, that wasn't really a catastrophical event.

    > >
    > > Out of curiosity - did you measure how much the "needlessly expensive"
    > > locking was slower than using a volatile? I'm asking because I find myself
    > > often in urge to invent all kind of clever tricks to bypass proper locking.

    >
    > No, but it was enough that the options were between writing 'volatile'
    > and several lines of code using a non-standard library to implement proper
    > locking, so the choice was rather clear to me.
    >
    > (In C++11 it might have been enough to declare the integral to be atomic,
    > and it would probably have been equally fast and fully synchronized. However,
    > I did not have C++11 at my disposal at that time.)


    I think MS did sense the need for multi-core programming in C#.

    But C++ is getting old to have a kid in the C family.
    88888 Dihedral, Jun 29, 2012
    #16
  17. ä¼è™Ž

    Cong Wang Guest

    On Tue, 26 Jun 2012 at 17:04 GMT, Victor Bazarov <> wrote:
    > On 6/26/2012 12:11 PM, ä¼è™Ž wrote:
    >> how to use volatile key word?
    >>
    >> Assume I have a global variable shared by two or more tasks. Do I
    >> need to declare it as volatile?

    >
    > 'volatile' usually means that the object's value can be changed at any
    > moment by some mechanism outside of your program control. When you have
    > a global variable shared between parts of *your program*, that's all
    > under your control, and hence doesn't need to be declared 'volatile'.
    >


    Right...

    Also check this doc:
    http://www.kernel.org/doc/Documentation/volatile-considered-harmful.txt

    even though it is for kernel, it applies to user-space applications as
    well.

    Thanks.
    Cong Wang, Jun 29, 2012
    #17
  18. ä¼è™Ž

    Mark Guest

    On Thu, 28 Jun 2012 15:27:55 -0300, Gerhard Fiedler
    <> wrote:

    >Mark wrote:
    >
    >> On Wed, 27 Jun 2012 16:12:05 -0500, Paavo Helde
    >> <> wrote:
    >>
    >>>Mark <> wrote in
    >>>news::
    >>>
    >>>>
    >>>>>See e.g. http://en.wikipedia.org/wiki/Volatile_variable
    >>>>
    >>>> This page does show cases where use of the volatile keyword is
    >>>> necessary.
    >>>
    >>> Not sure what you mean, for C and C++ I see only discussion about
    >>> memory- mapped hardware. The examples about multi-thread
    >>> synchronization with volatile are talking about Java and C# where
    >>> this keyword apparently means something different.

    >>
    >> As I understand it there is still a risk of the unsafe opimizations
    >> which the volatile keyword would prevent.

    >
    >While that's true, the memory barriers that come with synchronized
    >processor instructions, synchronization library functions/objects or the
    >new C++ synchronization mechanisms prevent these unsafe optimizations
    >also. That's why volatile is not necessary if you use these.


    We can't all rely on new features. I have to maintain code that needs
    to work on a large variety of different compilers (including quite old
    ones).
    --
    (\__/) M.
    (='.'=) If a man stands in a forest and no woman is around
    (")_(") is he still wrong?
    Mark, Jun 29, 2012
    #18
  19. Mark wrote:

    > On Thu, 28 Jun 2012 15:27:55 -0300, Gerhard Fiedler
    > <> wrote:
    >
    >>Mark wrote:
    >>
    >>> On Wed, 27 Jun 2012 16:12:05 -0500, Paavo Helde
    >>> <> wrote:
    >>>
    >>>>Mark <> wrote in
    >>>>news::
    >>>>
    >>>>>
    >>>>>>See e.g. http://en.wikipedia.org/wiki/Volatile_variable
    >>>>>
    >>>>> This page does show cases where use of the volatile keyword is
    >>>>> necessary.
    >>>>
    >>>> Not sure what you mean, for C and C++ I see only discussion about
    >>>> memory- mapped hardware. The examples about multi-thread
    >>>> synchronization with volatile are talking about Java and C# where
    >>>> this keyword apparently means something different.
    >>>
    >>> As I understand it there is still a risk of the unsafe opimizations
    >>> which the volatile keyword would prevent.

    >>
    >>While that's true, the memory barriers that come with synchronized
    >>processor instructions, synchronization library functions/objects or the
    >>new C++ synchronization mechanisms prevent these unsafe optimizations
    >>also. That's why volatile is not necessary if you use these.

    >
    > We can't all rely on new features. I have to maintain code that needs
    > to work on a large variety of different compilers (including quite old
    > ones).


    FWIW, I wasn't talking about new features /only/. Working
    implementations of pthread and compiler support for synchronized atomics
    have been around since long before C++11.

    Gerhard
    Gerhard Fiedler, Jun 29, 2012
    #19
  20. Scott Lurndal wrote:

    > Gerhard Fiedler <> writes:
    >>Mark wrote:
    >>
    >>> On Thu, 28 Jun 2012 15:27:55 -0300, Gerhard Fiedler
    >>> <> wrote:
    >>>
    >>>>Mark wrote:
    >>>>
    >>>>> On Wed, 27 Jun 2012 16:12:05 -0500, Paavo Helde
    >>>>> <> wrote:
    >>>>>
    >>>>>>Mark <> wrote in
    >>>>>>news::
    >>>>>>
    >>>>>>>
    >>>>>>>>See e.g. http://en.wikipedia.org/wiki/Volatile_variable
    >>>>>>>
    >>>>>>> This page does show cases where use of the volatile keyword is
    >>>>>>> necessary.
    >>>>>>
    >>>>>> Not sure what you mean, for C and C++ I see only discussion about
    >>>>>> memory- mapped hardware. The examples about multi-thread
    >>>>>> synchronization with volatile are talking about Java and C# where
    >>>>>> this keyword apparently means something different.
    >>>>>
    >>>>> As I understand it there is still a risk of the unsafe opimizations
    >>>>> which the volatile keyword would prevent.
    >>>>
    >>>>While that's true, the memory barriers that come with synchronized
    >>>>processor instructions, synchronization library functions/objects or the
    >>>>new C++ synchronization mechanisms prevent these unsafe optimizations
    >>>>also. That's why volatile is not necessary if you use these.
    >>>
    >>> We can't all rely on new features. I have to maintain code that needs
    >>> to work on a large variety of different compilers (including quite old
    >>> ones).

    >>
    >>FWIW, I wasn't talking about new features /only/. Working
    >>implementations of pthread and compiler support for synchronized atomics
    >>have been around since long before C++11.

    >
    > And working code using volatile has been around since long before
    > pthreads.


    So what? It seems to get more and more difficult to make a point that
    uses more than two sentences or 12 words... :)

    The line of arguments here is (I'm trying to stay under 12 words):

    (A) "volatile" is needed to prevent unsafe compiler optimizations.
    (B) Other methods also prevent unsafe optimizations.
    (A) I can't use these other methods because I can't use C++11.
    (B) Many of those other methods don't need C++11 features.

    I couldn't put the whole chain in 12 words, but maybe this shortened
    summary helps illustrate anyway why the fact that in some situations
    volatile works has nothing to do with this sub-thread.

    Gerhard
    Gerhard Fiedler, Jun 30, 2012
    #20
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. ben
    Replies:
    5
    Views:
    579
    Ulrich Eckhardt
    Jan 11, 2005
  2. M P
    Replies:
    1
    Views:
    451
  3. Sagar
    Replies:
    0
    Views:
    76
    Sagar
    Jan 18, 2006
  4. ä¼è™Ž

    how to use volatile key word?

    ä¼è™Ž, Jun 26, 2012, in forum: C Programming
    Replies:
    4
    Views:
    475
    Tim Rentsch
    Jun 27, 2012
  5. ä¼è™Ž

    how to use volatile key word?

    ä¼è™Ž, Jun 26, 2012, in forum: C++
    Replies:
    1
    Views:
    554
    Joshua Maurice
    Jul 2, 2012
Loading...

Share This Page