gpt4 book ai didi

delphi - 如何在TThread中设置堆栈大小?

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

如何在 TThread 中设置自定义堆栈大小?我正在尝试重新引入 TThread 的构造函数,但它说 ThreadProc 丢失,但它就在 System.Classes 中。

type
TThreadHelper = class helper for TThread
constructor Create(const CreateSuspended: Boolean = False; const StackSize: Integer = 0); reintroduce;
end;

{ TThreadHelper }

constructor TThreadHelper.Create(const CreateSuspended: Boolean; const StackSize: Integer);
begin
Self.FSuspended := not Self.FExternalThread;
Self.FCreateSuspended := CreateSuspended and not Self.FExternalThread;
if not Self.FExternalThread then
begin
Self.FHandle := BeginThread(nil, StackSize, @ThreadProc, Pointer(Self), CREATE_SUSPENDED, Self.FThreadID);
if Self.FHandle = 0 then
raise EThread.CreateResFmt(@SThreadCreateError, [SysErrorMessage(GetLastError)]);
end
else
begin
Self.FHandle := Winapi.Windows.GetCurrentThread;
Self.FThreadId := GetCurrentThreadId;
end;
end;

[dcc32 Error] Project5.dpr(29): E2003 Undeclared identifier: 'ThreadProc'

最佳答案

我不知道,是否可以在创建线程后设置堆栈大小。也许SetThreadStackGuarantee有帮助吗?

您可以使用BeginThread从头开始创建线程,但它相当复杂。我这里有一个使用Detours的解决方法。请注意,有多种 Detours 变体。我认为只有 Cromis.Detours 兼容 x64。

unit IndividualStackSizeForThread;

interface

uses
System.Classes,
Cromis.Detours { http://www.cromis.net/blog/downloads/cromis-ipc/ };

type
TThreadHelper = class helper for TThread
constructor Create(CreateSuspended: Boolean; StackSize: LongWord);
end;

implementation

var
TrampolineBeginThread: function(SecurityAttributes: Pointer; StackSize: LongWord;
ThreadFunc: TThreadFunc; Parameter: Pointer; CreationFlags: LongWord;
var ThreadId: TThreadID): THandle = nil;

threadvar
StackSizeOverride: LongWord;

function InterceptBeginThread(SecurityAttributes: Pointer; StackSize: LongWord;
ThreadFunc: TThreadFunc; Parameter: Pointer; CreationFlags: LongWord;
var ThreadId: TThreadID): THandle;
const
STACK_SIZE_PARAM_IS_A_RESERVATION = $00010000; // http://msdn.microsoft.com/en-us/library/windows/desktop/ms682453(v=vs.85).aspx
begin
if StackSizeOverride <> 0 then
begin
CreationFlags := CreationFlags or STACK_SIZE_PARAM_IS_A_RESERVATION;
StackSize := StackSizeOverride;
StackSizeOverride := 0;
end;

Result := TrampolineBeginThread(SecurityAttributes, StackSize, ThreadFunc,
Parameter, CreationFlags, ThreadId);
end;

constructor TThreadHelper.Create(CreateSuspended: Boolean; StackSize: LongWord);
begin
StackSizeOverride := StackSize;
inherited Create(CreateSuspended);
end;

initialization

TrampolineBeginThread := InterceptCreate(@BeginThread, @InterceptBeginThread);

finalization

InterceptRemove(@TrampolineBeginThread, @InterceptBeginThread);

end.

我不知道为什么 Embt 不允许程序员指定堆栈大小,如果有人知道原因,我会很感兴趣。

关于delphi - 如何在TThread中设置堆栈大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24140274/

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