Does Delphi have any equivalent to C's volatile variable?

前端 未结 5 553
走了就别回头了
走了就别回头了 2020-12-16 15:49

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 eq

5条回答
  •  眼角桃花
    2020-12-16 16:48

    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.

提交回复
热议问题