gpt4 book ai didi

multithreading - delphi中如何等待多个线程终止?

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

我有一个具有 50 个线程的应用程序,可以执行某些操作,并且我希望我的过程 (btnTestClick) 等待,直到所有线程都终止。我尝试过使用全局变量作为计数器并使用 WaitForMultipleObjects(threadCount, @threadArr, True, INFINITE); 但该过程永远不会等待所有线程终止。这是我的线程的样子:

TClientThread = class(TThread)
protected
procedure Execute; override;
public
constructor create(isSuspended : Boolean = False);
end;

这里是构造函数执行过程:

constructor TClientThread.create(isSuspended : Boolean);
begin
inherited Create(isSuspended);
FreeOnTerminate := True;
end;

procedure TClientThread.Execute;
var
begin
inherited;
criticalSection.Enter;
try
Inc(globalThreadCounter);
finally
criticalSection.Leave;
end;
end;

我的 OnButtonClick 是这样的:

procedure TMainForm.btnTestClick(Sender: TObject);
var
clientThreads : array of TClientThread;
i, clientThreadsNum : Integer;
begin
clientThreadsNum := 50;
SetLength(clientThreads, clientThreadsNum);
for i := 0 to Length(clientThreads) - 1 do begin // РЕДАКТИРАЙ !!
clientThreads[i] := TClientThread.Create(True);
end;
// here I will assign some variables to the suspended threads, but that's not important here
for i := 0 to Length(clientThreads) - 1 do begin
clientThreads[i].Start;
end;

WaitForMultipleObjects(clientThreadsNum, @clientThreads, True, INFINITE);
// do something after all threads are terminated
end;

最佳答案

您的代码如下:

WaitForMultipleObjects(clientThreadsNum, @clientThreads, True, INFINITE);

其中 clientThreads 的类型为:

array of TClientThread

现在,@clientThreads是动态数组的地址。这是指向第一个线程对象的指针的地址。但是您应该传递一个指向第一个线程句柄的指针,这是完全不同的。因此,您需要形成一个线程句柄列表:

var
ThreadHandles: array of THandle;
....
SetLength(ThreadHandles, Length(clientThreads));
for i := 0 to high(clientThreads) do
ThreadHandles[i] := clientThreads[i].Handle;
WaitForMultipleObjects(clientThreadsNum, Pointer(ThreadHandles), True, INFINITE);

如果您检查返回值,您会发现对 WaitForMultipleObjects 的调用不正确。 Win32 编程的一项基本规则(您应该努力不要违反的规则)是检查函数调用返回的值。

我相信您对 WaitForMultipleObjects 的调用将返回 WAIT_FAILED。发生这种情况时,您可以调用 GetLastError 来找出问题所在。您应该修改代码以执行正确的错误检查。请仔细阅读文档以了解如何执行此操作。

关于multithreading - delphi中如何等待多个线程终止?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23936905/

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