volatile

M

Marc Schellens

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
 
T

tom_usenet

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
 
T

tom_usenet

I should mention that some of the experts on this hang out in
comp.programming.threads

Tom
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,056
Latest member
GlycogenSupporthealth

Latest Threads

Top