multithreadingdelphithread-safety

Are Delphi simple types thread safe?


I declared two global variables:

var
  gIsRunning: Boolean = False;
  gLogCounter: Integer = 0;

These variables are written only in the main thread, and read in other threads. In this case, are these variables thread safe?


Solution

  • You are probably saying about atomic variables. Integer and Boolean variables are atomic. Booleans (bytes) are always atomic, integers (32-bits) are atomic because the compiler properly aligns them.

    Atomicity means that any read or write operation is executed as a whole. If a thread A executes atomic write and a thread B atomic read of the same data at the same time, the data read by thread B is always consistent - it is impossible that some bits read by thread B are obtained from the current write operation and some bits from the previous write (by thread A)

    But atomicity does not mean thread safety - you can easily write unsafe code with atomic variables. A variable itself cannot be threadsafe - only a code as a whole can be (or not) threadsafe.