volatile

Discussion in 'C++' started by Marc Schellens, Apr 27, 2004.

  1. When has a variable to be declared volatile?
    I have a program wich sets the variable through an
    interrupt. But its read only from within the same program.
    What if it would be multi-threaded?
    thanks,
    marc
     
    Marc Schellens, Apr 27, 2004
    #1
    1. Advertising

  2. Marc Schellens

    tom_usenet Guest

    On Tue, 27 Apr 2004 17:46:33 +0900, Marc Schellens
    <> wrote:

    >When has a variable to be declared volatile?


    When it might be modified asynchronously by something outside of the
    compiler's control, such as some hardware or another process (e.g.
    shared memory). Also, atomic variables (using platform specific atomic
    functions) should generally be volatile, at least on Win32, but you
    may need memory barriers in addition to ensure that a read value is
    the latest and a written value propogates to other processors on a
    multiprocessor system.

    >I have a program wich sets the variable through an
    >interrupt. But its read only from within the same program.


    If you set the value from an ISR and then read it from elsewhere in
    the code, then usually you should make the variable volatile, but your
    platform documentation should make this clear.

    >What if it would be multi-threaded?


    In general, volatile is neither necessary or sufficient for
    thread-safety. You need locking primitives (mutexes/critical sections)
    to safely share resources, or atomic primitives for single variables.
    All this is platform dependent though (although a lot of platforms
    have standardised on POSIX).

    Tom
    --
    C++ FAQ: http://www.parashift.com/c -faq-lite/
    C FAQ: http://www.eskimo.com/~scs/C-faq/top.html
     
    tom_usenet, Apr 27, 2004
    #2
    1. Advertising

  3. Marc Schellens

    tom_usenet Guest

    tom_usenet, Apr 27, 2004
    #3
    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. Knute Johnson

    Re: Volatile?

    Knute Johnson, Jul 1, 2003, in forum: Java
    Replies:
    17
    Views:
    1,467
    Knute Johnson
    Jul 3, 2003
  2. Doug Pardee

    Re: Volatile?

    Doug Pardee, Jul 1, 2003, in forum: Java
    Replies:
    0
    Views:
    907
    Doug Pardee
    Jul 1, 2003
  3. Replies:
    1
    Views:
    941
    Knute Johnson
    Aug 29, 2003
  4. Daniel

    Can volatile be trusted?

    Daniel, Sep 11, 2003, in forum: Java
    Replies:
    7
    Views:
    479
    Chris Uppal
    Sep 12, 2003
  5. ben
    Replies:
    5
    Views:
    605
    Ulrich Eckhardt
    Jan 11, 2005
Loading...

Share This Page