www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - how to stop a variable from being optimized out

reply "Rory" <rjmcguire gmail.com> writes:
Hi,


Is there a way I can stop "current" from being optimized out 
without using "volatile"?
The compiler is suggesting I replace "volatile" with 
"synchronized" but I don't want it synchronized?
Would a memory barrier work?

shared n = new int(value);
for (;;) {
   volatile auto current = payload; // payload is a shared variable
   if (current == payload) { // just to make sure we copied a 
complete value from
     if (current is null) {
       if (cas(&payload, current, n)) {
         return true;
       }
     }
   }
}


Thanks!
-Rory
Feb 23 2015
parent reply ketmar <ketmar ketmar.no-ip.org> writes:
On Tue, 24 Feb 2015 06:29:33 +0000, Rory wrote:

 Is there a way I can stop "current" from being optimized out without
 using "volatile"?
but why do you need this? just use `atomicLoad` to get shared variable=20 value, it will do the right caching.=
Feb 23 2015
parent reply "Rory" <rjmcguire gmail.com> writes:
On Tuesday, 24 February 2015 at 06:48:26 UTC, ketmar wrote:
 but why do you need this? just use `atomicLoad` to get shared 
 variable
 value, it will do the right caching.
Nice! Thanks. Tested atomicLoad and it is slightly faster for my non blocking queue.
Feb 24 2015
parent ketmar <ketmar ketmar.no-ip.org> writes:
On Tue, 24 Feb 2015 12:50:53 +0000, Rory wrote:

 On Tuesday, 24 February 2015 at 06:48:26 UTC, ketmar wrote:
 but why do you need this? just use `atomicLoad` to get shared variable
 value, it will do the right caching.
=20 Nice! Thanks. Tested atomicLoad and it is slightly faster for my non blocking queue.
just in case: by "do the right caching" i meant that this is memory=20 barrier, so compiler will not optimise your `current` away. i.e. the only=20 thing you have to change is this line: volatile auto current =3D payload; // payload is a shared variable to: auto current =3D atomicLoad(payload); i reread my answer and found that it may be not so obvious.=
Feb 24 2015