Talk:Volatile variable

From Wikipedia, the free encyclopedia

This article needs to be completely rewritten for the following reasons:

1) It confuses the problem of reading stale data with the problem of concurrent access. For example, it suggests that mutual exclusion is an alternative to using 'volatile'.

2) It fails to mention the two things that 'volatile' is actually both necessary and sufficient for, code that might be interrupted by a signal and code that uses 'longjmp'.

3) It talks about behavior that might happen to be true on some particular implementation as if it was guaranteed behavior.

4) It fails to mention that 'volatile' contains no atomicity guarantees whatsoever (except for reads of sig_atomic_t variables on single-threaded programs). So even if it guarantees that a change is noticed, it does not guarantee that the right value is read. (Rather than some bits of the old value and some of the new.) Foolishly, the example does not use 'sig_atomic_t'!

No solution short of rewriting will address these problems, IMO.

[edit] volatile pointer

Does C support volatile pointers? I does not mean pointers to volatile data. Same as const pointers (and pointer to constants). --89.49.193.114 20:35, 11 February 2007 (UTC)

[edit] Another example

Without use of the keyword "volatile" the following program - if optimized - will likely just print "value=0" because the code incrementing "value" is just optimized away. This is a somewhat interesting case because it does not involve an external modifier, special memory and no (obvious use of) setjmp.

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

static volatile sig_atomic_t value;

static void
sighandler(int sig)
{
  (void) sig;
  printf("value=%u\n", (unsigned) value);
  exit(EXIT_SUCCESS);
}

static void
increment(void)
{
  for (;;)
    value++;
}

int
main(void)
{
  signal(SIGALRM, sighandler);
  alarm(1);
  increment();
  return 0;
}

--82.141.49.88 02:38, 11 March 2007 (UTC)