You need to store a pointer to the variable.
type
TFreeAndNilThread = class(TThread)
private
FReferenceObj: ^TFreeAndNilThread;
end;
Then you need to pass in the reference in the constructor:
type
TFreeAndNilThread = class(TThread)
private
FReferenceObj: ^TFreeAndNilThread;
public
constructor Create(var ReferenceObj: TFreeAndNilThread);
end;
Then you can implement it like this:
constructor TFreeAndNilThread.Create(var ReferenceObj: TFreeAndNilThread);
begin
inherited Create(True);
FreeOnTerminate := True;
FReferenceObj := @ReferenceObj;
end;
When the thread dies you set the reference to nil
like this:
ReferenceObj^ := nil;
For convenience, since you'd likely treat this as a base class from which you derive other classes, you may prefer to make the parameter to the constructor untyped. You can just do that without making other changes to the code. When you do so the constructor looks like this:
constructor Create(var ReferenceObj);
This will only do you good if the code that sets the reference to nil
is in the same thread as all other code that attempts to reference MyThread
. Otherwise you will have a race condition.
I'm fairly sure that your idea is not the solution to your problem. However, the above does show you how to take a reference to a variable, which is what you asked for.