Jouni Aro
Jouni Aro

Reputation: 2139

How do I set a boolean value atomically in Delphi?

AtomicExchange requires an Integer or NativeInt variable, but how could I use it (or something similar) to set a boolean value in a thread-safe way - or is there any need for it?

Upvotes: 3

Views: 1847

Answers (1)

Remko
Remko

Reputation: 7340

A Delphi Boolean is a byte value and cannot be used with the Atomic API's as they operate on 32bit values.

You could use a BOOL instead which is a 32bit boolean like this:

var
  b: bool;
begin
  b := False;

  // true
  AtomicIncrement(Integer(b));

  // false
  AtomicDecrement(Integer(b));

However incrementing is a bit dangerous as incrementing it twice (similar to assigning True twice) and decrementing it once means the value is > 0 and thus still True.

An alternative might be this:

  // false
  AtomicExchange(Integer(b), Integer(False));

  // true
  AtomicExchange(Integer(b), Integer(True));

Upvotes: 5

Related Questions