views:

866

answers:

4

In C and C++ a variable can be marked as volatile, which means the compiler will not optimize it because it may be modified external to the declaring object. Is there an equivalent in Delphi programming? If not a keyword, maybe a work around?

My thought was to use Absolute, but I wasn't sure, and that may introduce other side effects.

+1  A: 

I don't know of any equivalent, nor do I think that the absolute directive will help you. absolute allows you to have two variables that use the same address, but I do not think it will prevent the compiler from optimising references to that memory.

I imagine you could use a pointer and manage it yourself. That way whatever the compiler does as far as optimising retrival of the pointer value, it should not assume the value stored at the address is the same as last time it read it, but this is pure speculation.

Richard A
+7  A: 

Short answer: no.

However, I am not aware of any situation in which the conservative approach of the compiler will change the number of reads or writes if you follow this approach:

When reading a cross-thread visible location, save its value to a local before doing any further manipulation; similarly, restrict writes to a single assignment.

The Delphi compiler does not perform common subexpression elimination (CSE) on non-local location expressions when there are calls to non-inlined methods between the expressions, as the compiler doesn't do interprocedural optimization and thus it would not be correct even for single-threaded code.

So, you may want to use InterlockedExchange() to do your reads and writes to force this; additionally, this will cause a full memory barrier, so the processor won't reorder reads and writes either.

Barry Kelly
A: 

Use dynamically allocated pointers?

var
  MyVarPtr: ^integer;
begin
  New(MyVarPtr);
  MyVarPtr^ := 5;
...

This should keep the compiler from using a register for the integer value (but it might still use one for the address). I am not sure how that compares to volatile, though.

Thomas Mueller
+1  A: 

Delphi for .Net does not have the keyword either, but the .Net platform has util functions for it. See Thread.VolatileRead and Thread.VolatileWrite.

Lars Truijens