gpt4 book ai didi

multithreading - 我可以在 `Inherited Create` 之前做一些初始化吗?

转载 作者:行者123 更新时间:2023-12-03 12:48:04 26 4
gpt4 key购买 nike

我想创建和启动一个线程,全部使用一个命令行 TClientCopyThread.Create(...)。为此,我必须使用 Suspended = False 创建线程,以便它可以立即运行。我知道当我写一个新对象的constructor时,首先我必须调用inherited Create以便创建对象的实例,然后做我的初始化。但是在这里,如果我调用 inherited,线程将在没有初始化参数的情况下启动。我尝试最后调用 inherited,它似乎工作正常(我没有收到任何访问冲突),但我不确定这是否是巧合。

  TClientCopyThread = class(TThread)
private
OwnGUID: String;
SrcPath, DestPath: String;
Files: TFileNames;
RemoveIt: Boolean;
protected
procedure Execute; override;
public
constructor Create(const GUID, ASrcPath, ADestPath: String;
const FileNames: TFileNames; RemoveSrc: Boolean);
end;

constructor TClientCopyThread.Create(const GUID, ASrcPath, ADestPath: String;
const FileNames: TFileNames; RemoveSrc: Boolean);
var I: Integer;
begin
SrcPath:= Copy(ASrcPath, 1, Length(ASrcPath));
DestPath:= Copy(ADestPath, 1, Length(ADestPath));
SetLength(Files, Length(FileNames));
for I:= 0 to High(Files) do
Files[I]:= Copy(FileNames[I], 1, Length(FileNames[I]));
RemoveIt:= RemoveSrc;
FreeOnTerminate:= True;
inherited Create;
end;

最佳答案

要回答您的具体问题 - 是的,您可以调用 inherited Create在派生构造函数期间的任何时候。它不需要是第一条语句(与 inherited Destroy 相同,作为析构函数中的最后一条语句)。在调用任何 构造函数之前,类对象的内存已经完全分配,因此在调用 inherited 之前初始化派生类的成员是安全的。构造函数。但是,当从派生构造函数访问基类成员时,您应该调用 inherited构造函数首先在访问它们之前初始化它们。

话虽如此,您对 TThread 的理解构造函数的工作完全是错误的。自 Delphi 6 起,基类 TThread构造函数总是 在挂起模式下创建底层操作系统线程,然后在 TThread.AfterConstruction() 中恢复线程在所有 构造函数完全退出后,如果 TThread对象是用 CreateSuspended=False 构造的.所以,你声称调用 inherited CreateCreateSuspended=False自 2001 年发布 Delphi 6 以来,立即 将启动线程运行并不是真的。在您的 TClientCopyThread.Create() 之后,底层操作系统线程将不会开始运行,之后构造函数已经退出。因此,您的 Execute()方法永远不会作用于未初始化的成员,不管你如何设置CreateSuspended .

您所描述的(在初始化成员之前运行的线程)是 Delphi 5 和更早版本中的一个错误,该错误已在 Delphi 6 中修复。

关于multithreading - 我可以在 `Inherited Create` 之前做一些初始化吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63962703/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com