Thanks. Hadn't thought of that before. It is of course quite possible
for it to be constructed 2 times. Going back to that code sample I
posted for observation I use this method for creating a Critical
Section. This would probably be a good place to use that seeing as I use
that in a very threaded environment.

-----Original Message-----
From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED]
On Behalf Of Jeremy North
Sent: Friday, 19 May 2006 2:29 p.m.
To: NZ Borland Developers Group - Delphi List
Subject: Re: [DUG] Usage - initialization and finalization

An alternate and thread safe way to perform this operation is to use
InterlockedCompareExchange.

It is possible (although not very probable) to have FList created
twice without using InterlockedCompareExchange. Probably not worth the
extra effort though.

ms-help://borland.bds4/dllproc/base/interlockedcompareexchange.htm

This technique is implemented in the TPrivateHeap class in the
PrivateHeap unit. It was originally written by Hallvard Vassbotn. If
you are interested in the inner workings of Delphi and the Compiler,
you should read his blog (http://hallvards.blogspot.com/).

For the OP I would minimize the use of the Initialization section to
cases where you really need it. Otherwise your unit cannot be smart
linked out.

/// code below

unit Unit4;

interface

uses
    Windows
  , Classes
  , SysUtils
  ;

function GetList: TList;

implementation

var
  FList: TList;

function GetList: TList;
var
  lList: TList;
begin
  if FList = nil then
  begin
    lList := TList.Create;
    if InterlockedCompareExchange(Integer(FList), Integer(lList), 0) <>
0 then
      lList.Free;
  end;
  result := FList;
end;

initialization

finalization
  FreeAndNil(FList);

end.

_______________________________________________
Delphi mailing list
[email protected]
http://ns3.123.co.nz/mailman/listinfo/delphi



_______________________________________________
Delphi mailing list
[email protected]
http://ns3.123.co.nz/mailman/listinfo/delphi

Reply via email to