As I known, there are two common kinds of practices to ensure the thread safety of lazy-initialization:
- Double-checked locking (Marks the variable as volatile to avoid the memory ordering)
- InterlockedCompareExchangePointer
It seems VCL uses the second practice. Is there any reason?
class function TEncoding.GetUTF8: TEncoding;
var
LEncoding: TEncoding;
begin
if FUTF8Encoding = nil then
begin
LEncoding := TUTF8Encoding.Create;
if InterlockedCompareExchangePointer(Pointer(FUTF8Encoding), LEncoding, nil) <> nil then
LEncoding.Free;
end;
Result := FUTF8Encoding;
end;
or is there any better method?
Thanks!