我有
var H: array of THandle;
Run Code Online (Sandbox Code Playgroud)
然后在一个循环中创建多个线程,并将线程句柄分配给 H 的元素,然后等待它们。将@H[0] 作为第二个参数传递给下面的 WFMO 有效。
WaitForMultipleObjects(Length(H), @H[0], True, INFINITE) <-- Works
Run Code Online (Sandbox Code Playgroud)
但是传递@H 如下失败,WAIT_FAILED。GetLastError 返回“无效句柄”。
WaitForMultipleObjects(Length(H), @H, True, INFINITE) <--- Fails.
Run Code Online (Sandbox Code Playgroud)
为什么@H 与@H[0] 不同?
我正在创建一个线程,然后说要等待它以 WFSO 调用终止(下面是简化的伪代码,显然没有人想在创建线程后立即等待它)。
constructor TFileScannerThread.Create(Parameters)
begin
/// assign parameters to private variables, and call
inherited Create(true); //Create Suspended
FreeOnTerminate := true;
Start;
end;
Run Code Online (Sandbox Code Playgroud)
在主线程中
fst := TFileScannerThread.Create(BaseFolder, ScanMode, AbortEvent);
/// I presume, the next call would block the main thread until the child thread is done
/// but, it seems to create a deadlock & WFSO never returns
/// I get a WAIT_TIMEOUT if I use a finite wait time
WaitForsingleObject(fst.Handle, INFINITE);
Run Code Online (Sandbox Code Playgroud)
我做错了什么/错过了什么?如果我没有 WFSO,线程会在大约 10 秒内完成。
编辑:使用 FreeOnTerminate=false 创建不会产生此问题。