Is FormatDateTime thread safe when using the same copy of TFormatSettings across multiple threads?

736 views Asked by At

I've read a lot about thread safety when reading variable simultanously from multiple threads but I am still not sure whether my case is fine or not.

Consider that I have:

const
  MySettings: TFormatSettings =
    (
      CurrencyFormat   : 0;
      NegCurrFormat    : 0;
      ThousandSeparator: ' ';
      DecimalSeparator : '.';
      CurrencyString   : 'ยค';
      ShortDateFormat  : 'MM/dd/yyyy';
      LongDateFormat   : 'dddd, dd MMMM yyyy';

      //All fields of record are initialized.
    );

Can I use FormatDateTime('dd/mm/yyyy hh:nn:ss', MySettings, Now) in multiple threads without worries or should I spawn a separate copy of MySettings for each thread?

2

There are 2 answers

7
LU RD On BEST ANSWER

Yes this is perfectly safe.

As long as MySetting is not changed this is the way to use FormatDateTime and other similar procedures.

From documentation, System.SysUtils.TFormatSettings:

A variable of type TFormatSettings defines a thread-safe context that formatting functions can use in place of the default global context, which is not thread-safe.


N.B. You must provide this thread-safe context by programming. It is thread-safe only if you ensure that the parameter and its shares is not changed during execution.

Typically my serializing libraries are using a shared constant format setting variable, which provides a stable read/write interface in all locales.

7
David Heffernan On

This scenario is threadsafe if and only if the format settings record is not modified during the simultaneous calls to formatting functions.

Indeed the old school formatting functions that used a shared global format settings record were threadsafe if and only if the shared object was not modified. This is the key point. Is the format settings object modified or not?

My take on all this is that you should avoid modifying format settings objects. Initialise them and then never modify them. That way you never have thread safety issues.