But why the 'volatile' declarations |
The
volatile
modifier tells the compiler to not do funny things with the variable for optimization purposes, such as caching it, doing operations involving it out of order, or even completely removing its operations, among other things.
Observe the following:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
//Code A
bool someBool = false; //Line 1
someBool = false; //Operation A
if(someBool) //Operation B
{
doSomeStuff();
}
else
{
doSomeOtherStuff();
}
|
If you were a compiler optimizing for speed, what would you do if you saw Operations A and B above? Well, at Operation A,
someBool
was already set to
false
. And presumably,
someBool
did not change between Line 1 and Operation A. A compiler optimizing for speed would simply remove Operation A entirely (effectively removing a needless move instruction at the assembly level). What about Operation B?
someBool
is guaranteed to be
false
here, because presumably,
someBool
did not change between Operations A and B, so why do the
if
statement at all? This will save a jump instruction at the assembly level.
Now, our optimized code is the following:
1 2 3 4 5
|
//Code B
bool someBool = false;
doSomeOtherStuff();
|
Much nicer isn't it?
Now, if we had declared
bool someBool
as
volatile bool someBool
, we would have a guarantee that all operations involving
someBool
would be just as they are in code. If we had typed in Code A above, then the compiler would leave it alone.
Now,
volatile
comes into play with multi-threaded code. Let's say we have Code A above, and then the compiler optimized it to Code B. Now, let's also say that this code is accessed by multiple threads. Let's say one thread sets
someBool
to
false
but then there's a context switch right before Operation B (which got optimized out!) What if some other thread sets
someBool
to
true
? Well, we would have a synchronization issue because the first thread would come back and call
doSomeOtherStuff
when it should have called
doSomeStuff
! If
someBool
were declared
volatile
this type of synchronization problem wouldn't happen.
You know how I said the following above?
shacktar wrote: |
---|
And presumably, someBool did not change between Line 1 and Operation A. A compiler optimizing for speed would simply remove Operation A entirely |
shacktar wrote: |
---|
because presumably, someBool did not change between Operations A and B, so why do the if statement at all? |
In a nutshell, with multithreaded code, the above assumptions are invalid and thus compiler optimizations can lead to synchronization problems.
Had to change the Sleep(100) to Sleep(1000) to allow all the threads to execute |
Maybe you have a slower CPU than
m4ster r0shi.
Also what is the best way to share variables between processes'? Am using File/Mem mapping but is there a better way? |
That's one way to do it. Another way is to have one process open a socket and listen at a particular port and have the processes communicate data through that connection.