Skip to content

RE: Thread-safe Format

Oh, the joy of writing multiple threaded applications. I like this little tip that will keep string formatting calls from stepping over each other.

The Format function isn’t thread-safe unless you use the overload which takes a FormatSettings argument (because the FormatSettings-less version uses global variables). I use it to compose error messages in a thread I’m writing, and I want to use the same FormatSettings as the user would normally see in a GUI app. So here’s what I did. I added a TFormatSettings field to my thread class:

TMyThread = class(TThread)
private
FFormatSettings: TFormatSettings;
protected
procedure Execute; override;
end;

Then I set it at the start of the Execute method:

procedure TMyThread.Execute;
begin
GetLocaleFormatSettings(LOCALE_SYSTEM_DEFAULT, FFormatSettings);
end;

This seems to work well.

[Via Craig Stuntz’s Weblog]