Search code examples
multithreadingdelphidelphi-6

Is a class member free of cache line issue?


In the TThread class there is a class member (property) named Terminated.
There is also an procedure Terminate; which merely sets Terminated to True.
When we inherit from TThread there are some cases where we check for terminated. The following pool/loop is just to demonstrate a possible situation:

  while not Terminated do
  begin
    Work;
  end;

What is the garantee that terminated will never be cached by the processor?


Solution

  • The Delphi compiler is not at all aggressive in its optimisations. It treats members of classes as being global. That means, essentially, not local. The compiler knows that other parties can see the variable. Unlike a simple local variable.

    And for global variables, the compiler will not enregister its access of that variable. So whenever you read the variable the value is read from memory. Likewise when writing, the value is written to memory.

    All that remains is the memory caching. The memory system ensures consistency between the different processor caches.

    So, there is no problem with the TThread implementation of termination.