473,748 Members | 2,328 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Volatile variables

Hi,
Is there any chance that a program doesn' work properly even after a
variable is declared as volatile? I remember somebody mentioning a
scenario involving L1, L2 caches. Could anybody throw some light on
this?

Thanks,
Srinivas
Nov 14 '05 #1
11 2141
sr************* @yahoo.com (srinivas reddy) writes:
Hi,
Is there any chance that a program doesn' work properly even after a
variable is declared as volatile? I remember somebody mentioning a
scenario involving L1, L2 caches. Could anybody throw some light on
this?


If the program is incorrect to start with, there is a large (usually
close to one) chance that it will continue to not work properly if it
is changed so that some variables are volatile qualified. OTOH, if a
correct program is modified in this way, it will always continue to
work, although it might run slower.

Martin
--
,--. Martin Dickopp, Dresden, Germany ,= ,-_-. =.
/ ,- ) http://www.zero-based.org/ ((_/)o o(\_))
\ `-' `-'(. .)`-'
`-. Debian, a variant of the GNU operating system. \_/
Nov 14 '05 #2
On Fri, 27 Feb 2004 09:01:16 UTC, sr************* @yahoo.com (srinivas
reddy) wrote:
Hi,
Is there any chance that a program doesn' work properly even after a
variable is declared as volatile? I remember somebody mentioning a
scenario involving L1, L2 caches. Could anybody throw some light on
this?


Sure. The programmer can produce bugs in his code. There is no
guarantee than a program is 100% errorfree.
--
Tschau/Bye
Herbert

Visit http://www.ecomstation.de the home of german eComStation

Nov 14 '05 #3
In <ff************ **************@ posting.google. com> sr************* @yahoo.com (srinivas reddy) writes:
Is there any chance that a program doesn' work properly even after a
variable is declared as volatile?
If a program was correct before declaring anything as volatile, it will
keep being correct after and will produce the same output, unless the
output depends on unspecified behaviour. The only purpose of volatile is
to dumb down the compiler, WRT certain optimisations otherwise allowed by
the language.

OTOH, there are programs that aren't correct in the absence of the
volatile qualifier and that are fixed this way. Here's an example:

#include <stdio.h>
#include <signal.h>

sig_atomic_t gotsig = 0;

void handler(int signo)
{
gotsig = signo;
}

int main()
{
signal(SIGINT, handler);
puts("Press the interrupt key to exit.");
while (gotsig == 0) ;
printf ("The program received signal %d.\n", (int)gotsig);
return 0;
}

Because gotsig is not volatile, the compiler is free to "optimise" the

while (gotsig == 0) ;

loop to:

if (gotsig == 0) while (1) ;

since it sees no way the value of gotsig can change inside the loop.

If gotsig is volatile, the compiler must assume that its value can change
behind its back and keep testing its value.

But this doesn't mean that it's worth trying to fix broken programs by
randomly throwing in volatile qualifiers. As usual, there is no
substitute for knowing what you're doing.
I remember somebody mentioning a
scenario involving L1, L2 caches. Could anybody throw some light on
this?


Whoever mentioned such a scenario was heavily confused and in dire need
of a clue. The abstract C machine has no caching, therefore caching is
irrelevant to the correct behaviour of a C program.

Another typical example of using volatile is when writing memory testing
programs. Such programs often write values in memory and then read them
back and compare with the original. To the compiler, it is obvious what
the result of the comparison should be, so it can optimise all the memory
testing away and declare that the memory works correctly. To force the
writing to and the reading from memory, you *have* to use a pointer to
volatile data.

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 14 '05 #4
>In <ff************ **************@ posting.google. com>
sr************ *@yahoo.com (srinivas reddy) writes: [snippage]
I remember somebody mentioning a scenario involving L1, L2 caches.
Could anybody throw some light on this?


In article <news:c1******* ****@sunnews.ce rn.ch>
Dan Pop <Da*****@cern.c h> writes:
[a lot of correct answers to stuff I snipped, then:]Whoever mentioned such a scenario was heavily confused and in dire need
of a clue. The abstract C machine has no caching, therefore caching is
irrelevant to the correct behaviour of a C program.


I would not go so far as to say *this*. The second sentence is
true but does not imply the first, because the program might not
be written in Standard C after all.

In particular, one place one commonly abandons Standard C in order
to get actual work done :-) on real machines has to do with device
drivers, where the "volatile" keyword is also heavily used. Device
drivers tend to "do I/O" (reading input and generating output is
often required to get work done), and some machines provide fast
I/O methods ("DMA" and the like) that completely bypass the CPU.

If a CPU has an on-chip cache[1], and if DMA bypasses the CPU
entirely[2], then DMA bypasses the on-chip cache. As it happens,
on-chip CPU caches generally come in one of two flavors, called
"write-through" and "write-back". In the case of a write-through
cache, DMA *output* (from memory to device) does not require any
special action, because data in the CPU cache is always also in
memory (this is the property that makes the cache "write-through").
When the device obtains the output-data from memory, it gets the
desired values. DMA *input*, however, has a problem; and with
write-back caches, even DMA output has the same problem: the data
in the CPU cache can differ from that in memory, before and/or
after the device's DMA transaction. To obtain correct co-operation
between the device and the CPU we use steps called "cache flushing".
(In the abstract model I implemented for BSD, we always do this
twice for every DMA transaction: one "pre-op" and one "post-op",
supplying flags as to whether the op is read, write, or both.)

Again, just as Dan Pop said, all of this is outside the model we
use in ANSI/ISO C (the "abstract machine") -- but it does occur in
"real world" C programming, in a place where the "volatile" keyword
is used quite a lot.

[1] Most do these days; some have multiple levels of on-chip cache.

[2] Some do, some do not; some CPUs even have bugs in the DMA
snooping hardware. Sometimes some DMA goes through some caches
and bypasses others. Some of the more byzantine architectures have
multiple levels of I/O adapters, which have their own memory-interaction
issues. Making devices "upcall" to their adapters to announce
"intent to do I/O" and "finished doing I/O" removes all a lot of
"hair" from the drivers; the adapters do any setup or teardown
required and continue to push the call up their own chain until it
reaches a level that is "all-knowing".
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: forget about it http://web.torek.net/torek/index.html
Reading email is like searching for food in the garbage, thanks to spammers.
Nov 14 '05 #5

"srinivas reddy" <sr************ *@yahoo.com> wrote in message
news:ff******** *************** ***@posting.goo gle.com...
Hi,
Is there any chance that a program doesn' work properly even after a
variable is declared as volatile? I remember somebody mentioning a
scenario involving L1, L2 caches. Could anybody throw some light on
this?

Thanks,
Srinivas


Well, your post is a little vague.

One issue I have seen in the past is the following.

volatile char * p = addr1;
volatile char * q = addr2;

*p = 0x01;
*q = 0x00;

or

x = *p;
y = *q;

If addr1 and addr2 are addresses on some hardware device, the code may only
work correctly if the specified order happens.
Is the compiler required to insert code (eieio on some architectures) to
insure that the two memory locations are accessed in the order according to
the C standard (there is a sequence point between the two statements).
Modern architectures with multiple caches typically allow the above reads or
writes to happen in any order (more accurately, they don't guarantee the
order in which they happen).

The C99 Standard says in 5.1.2.3:
"At sequence points, volatile objects are stable in the sense that previous
accesses are
complete and subsequent accesses have not yet occurred."

Personally I believe a compiler is required to insert eieio. But I have seen
some not doing it.
Carsten Hansen
Nov 14 '05 #6
In article <news:K1******* **************@ bgtnsc05-news.ops.worldn et.att.net>
Carsten Hansen <ha******@world net.att.net> writes (in part):
Personally I believe a compiler is required to insert eieio. But I have seen
some not doing it.


While EIEIO instructions are specific to PowerPC architectures, in
general I am not sure I would *want* such instructions for all
"volatile" accesses. In particular, compare the loops in:

struct software_state *ss;
struct hardware_regist er *reg;

ss->polling = 1;
while (ss->ready == 0)
continue;

reg->cmd = RESET;
while (reg->csr & BUSY)
continue;

(and assume a single CPU). In the first case, the same CPU will be
reading and writing the "polling" and "ready" fields, and there is
no need for an I/O synchronization instruction. In the second case,
the hardware will be controlling the BUSY bit based on the command,
and there is a need for an I/O synchronization instruction.

I do not remember offhand whether EIEIO in particular is a privileged
instruction, but if it is -- and some architectures do have protected
"I/O flush" instructions -- and the compiler always generated it
for every "volatile" access, one could not even write proper ANSI
C "volatile sig_atomic_t" code. If the compiler-writer makes
"volatile" do everything, it often does too much; if not, it often
does too little. "Too little", however, can be augmented, while
"too much" is hard to undo afterward. :-)
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: forget about it http://web.torek.net/torek/index.html
Reading email is like searching for food in the garbage, thanks to spammers.
Nov 14 '05 #7
I think I didn't phrase my question properly. My program needs to have
a volatile variable to work correctly and there are no bugs in the
code. Now even if a variable declared as volatile, could program fail
to read the modified value of volatile variable? Would compiler store
volatile vaiable in cache? If so, then two processes cache same
volatile variable at two different locations. One process can't see
other process's modification unless variable id flushed fro cache to
memory (cache is implemented using write-back policy, so memory dont
have updated value)?
Da*****@cern.ch (Dan Pop) wrote in message news:<c1******* ****@sunnews.ce rn.ch>...
In <ff************ **************@ posting.google. com> sr************* @yahoo.com (srinivas reddy) writes:
Is there any chance that a program doesn' work properly even after a
variable is declared as volatile?


If a program was correct before declaring anything as volatile, it will
keep being correct after and will produce the same output, unless the
output depends on unspecified behaviour. The only purpose of volatile is
to dumb down the compiler, WRT certain optimisations otherwise allowed by
the language.

OTOH, there are programs that aren't correct in the absence of the
volatile qualifier and that are fixed this way. Here's an example:

#include <stdio.h>
#include <signal.h>

sig_atomic_t gotsig = 0;

void handler(int signo)
{
gotsig = signo;
}

int main()
{
signal(SIGINT, handler);
puts("Press the interrupt key to exit.");
while (gotsig == 0) ;
printf ("The program received signal %d.\n", (int)gotsig);
return 0;
}

Because gotsig is not volatile, the compiler is free to "optimise" the

while (gotsig == 0) ;

loop to:

if (gotsig == 0) while (1) ;

since it sees no way the value of gotsig can change inside the loop.

If gotsig is volatile, the compiler must assume that its value can change
behind its back and keep testing its value.

But this doesn't mean that it's worth trying to fix broken programs by
randomly throwing in volatile qualifiers. As usual, there is no
substitute for knowing what you're doing.
I remember somebody mentioning a
scenario involving L1, L2 caches. Could anybody throw some light on
this?


Whoever mentioned such a scenario was heavily confused and in dire need
of a clue. The abstract C machine has no caching, therefore caching is
irrelevant to the correct behaviour of a C program.

Another typical example of using volatile is when writing memory testing
programs. Such programs often write values in memory and then read them
back and compare with the original. To the compiler, it is obvious what
the result of the comparison should be, so it can optimise all the memory
testing away and declare that the memory works correctly. To force the
writing to and the reading from memory, you *have* to use a pointer to
volatile data.

Dan

Nov 14 '05 #8

"Chris Torek" <no****@torek.n et> wrote in message
news:c1******** *@enews2.newsgu y.com...
In article <news:K1******* **************@ bgtnsc05-news.ops.worldn et.att.net> Carsten Hansen <ha******@world net.att.net> writes (in part):
Personally I believe a compiler is required to insert eieio. But I have seensome not doing it.


While EIEIO instructions are specific to PowerPC architectures, in
general I am not sure I would *want* such instructions for all
"volatile" accesses. In particular, compare the loops in:

struct software_state *ss;
struct hardware_regist er *reg;

ss->polling = 1;
while (ss->ready == 0)
continue;

reg->cmd = RESET;
while (reg->csr & BUSY)
continue;

(and assume a single CPU). In the first case, the same CPU will be
reading and writing the "polling" and "ready" fields, and there is
no need for an I/O synchronization instruction. In the second case,
the hardware will be controlling the BUSY bit based on the command,
and there is a need for an I/O synchronization instruction.

I do not remember offhand whether EIEIO in particular is a privileged
instruction, but if it is -- and some architectures do have protected
"I/O flush" instructions -- and the compiler always generated it
for every "volatile" access, one could not even write proper ANSI
C "volatile sig_atomic_t" code. If the compiler-writer makes
"volatile" do everything, it often does too much; if not, it often
does too little. "Too little", however, can be augmented, while
"too much" is hard to undo afterward. :-)
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: forget about it http://web.torek.net/torek/index.html
Reading email is like searching for food in the garbage, thanks to

spammers.
In the code
reg->cmd = RESET;
while (reg->csr & BUSY)
continue;
how do you guarantee that the read from reg->csr happens after the write to
reg->cmd at the physical level without some I/O synchronization ?

It is not the CPU's load and store instructions that do the actual read and
write to physical memory.
The way I see it, you issue a write to a memory location, then you do a read
from a different memory location. Since the two memory locations are
different that can happen in any order on a modern architectures.
But if you are actually controlling hardware, the order can be essential as
I'm sure you are aware of.

I agree that you don't need it in all instances. And since it will cause a
penalty it is kind contrary to the spirit of C.
Carsten Hansen
Nov 14 '05 #9
On 27 Feb 2004 18:16:45 -0800, sr************* @yahoo.com (srinivas
reddy) wrote in comp.lang.c:

Do not top post, it makes discussions in technical groups very
difficult to follow and is considered rude. New material you add goes
after the relevant material you are quoting.
I think I didn't phrase my question properly. My program needs to have
a volatile variable to work correctly and there are no bugs in the
code. Now even if a variable declared as volatile, could program fail
to read the modified value of volatile variable? Would compiler store
volatile vaiable in cache? If so, then two processes cache same
volatile variable at two different locations. One process can't see
other process's modification unless variable id flushed fro cache to
memory (cache is implemented using write-back policy, so memory dont
have updated value)?


The following is a list of things that are neither defined nor
supported by the C standard:

- cache

- process

If your system provides these extensions and they cause a C program to
behave in a non-conforming manner, file a defect report with the
compiler vendor. Otherwise ask about these issues in a
compiler-spefic support group. This is not a language question.

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://www.eskimo.com/~scs/C-faq/top.html
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.l earn.c-c++
http://www.contrib.andrew.cmu.edu/~a...FAQ-acllc.html
Nov 14 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

17
7062
by: Radde | last post by:
HI, Can volatile variables be accessed by many processess..or only one process can access it.. Cheers..
7
3217
by: r_o_h_i_t | last post by:
Can anybody please tell me the complete properties if volatile variables in C. And what are specific uses of them? Thanks in advance.
14
19357
by: google-newsgroups | last post by:
Hello, even (or because?) reading the standard (ISO/IEC 9899/1999) I do not understand some issues with volatile. The background is embedded programming where data is exchanged between main program flow and interrupts. At the organisation I work, instead of declaring a variable volatile, it is casted to volatile when necessary:
22
2307
by: Assaf | last post by:
hi all i know that i should not cross-post, but i am not sure to which group to post this question. 2 quesions about volatile: 1. i use volatile when 2 threads access the same variable is this the proper use of volatile?
6
3225
by: Clausfor | last post by:
Hello, I have a problem with restoring variables in the setjmp/longjmp functions: K&R2 for longjmp says: "Accessible objects have the same value they had when longjmp was called, except for automatic non volatile variables of the function invoking setjmp, these will be undefined if modified after the setjmp call"
6
3533
by: titan nyquist | last post by:
Can you make volatile structures in C#? I have a static class, to have "global" variables. This allows the whole program to see them. I make them "volatile" to avoid multi- threading accessing issues. That works. THE PROBLEM: In that static class, I want to combine some variables inside a structure, and then make a variable of that structure type,
94
30335
by: Samuel R. Neff | last post by:
When is it appropriate to use "volatile" keyword? The docs simply state: " The volatile modifier is usually used for a field that is accessed by multiple threads without using the lock Statement (C# Reference) statement to serialize access. " But when is it better to use "volatile" instead of "lock" ?
10
3434
by: S James S Stapleton | last post by:
Is volatile necessary anymore? I have a two-thread piece of code I've been testing to figure out what volatile does (fairly simple code, uses pthreads). I have an update thread (variables passed as volatile) and a print thread (one variable volatile, the other, not). There is no difference in the behavior of the volatile and nonvolatile thread. I'm compiling this with gcc, using the -O2 and -pthreads flags. The sudocode is at the end....
16
1834
by: Ark Khasin | last post by:
I have a memory-mapped peripheral with a mapping like, say, struct T {uint8_t read, write, status, forkicks;}; If I slap a volatile on an object of type struct T, does it guarantee that all accesses to the members are byte-wide, or is the compiler free to read or read-modify-write in any data width it chooses? Is slapping a volatile on each member of the struct definition any different? better? worse?
3
2326
by: C++Liliput | last post by:
It seems that the keyword "volatile" is used to make sure that threads reading (or writing to) the same data should see a consistent picture of the variable i.e. updates made to the common data should immediately get reflected to other threads that are using it. However I have never faced this issue in y multi-threaded code even though the common variables are not declared volatile. So is this just a matter of coincidence that I have had...
0
8822
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9528
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9236
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8235
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6072
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4592
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4863
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3298
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2774
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.