C++线程的可用堆栈大小

Available stack size for C++ thread

本文关键字:堆栈 线程 C++      更新时间:2023-10-16

我使用Windows 10,Visual Studio 2019 程序生成线程。我需要添加功能,指出在任何执行时间内可用的堆栈大小。

#include <iostream>
#include <thread>
void thread_function()
{
//AvailableStackSize()?  
//Code1 //varibales on stack allocation + function call
//AvailableStackSize()? it should decrease
//Code2 //varibales on stack allocation + function call
//AvailableStackSize()? it should decrease
//Code3 //varibales on stack allocation + function call
//AvailableStackSize()? it should decrease
}
int main()
{
std::thread t(&thread;_function);
std::cout << "main threadn";
std::thread t2 = t;
t2.join();
return 0;
}

我尝试使用.但我不确定我该如何进行。我只能查询堆栈的总大小是多少。不可用的。

bool AvailableStackSize()
{
// Get the stack pointer
PBYTE pEsp;
_asm {
mov pEsp, esp
};
// Query the accessible stack region
MEMORY_BASIC_INFORMATION mbi;
VERIFY(VirtualQuery(pEsp, &mbi, sizeof(mbi)));
return mbi.RegionSize;//This is a total size! what is an available? Where guard is located?
}

可能我还可以检查堆栈内是否有某个地址

PVOID add;
(add>= mbi.BaseAddress) && (add < PBYTE(mbi.BaseAddress) + mbi.RegionSize);

我看到了几个类似的问题,但没有人100%回答这个问题。 获取可用堆栈大小的正确方法是什么?

由于堆栈向下增长,因此这是堆栈的潜在底部与当前使用的末尾之间的差异。 顺便说一句,您不需要任何内联程序集,因为您知道局部变量被放置在堆栈上。

__declspec(noinline) size_t AvailableStackSize()
{
// Query the accessible stack region
MEMORY_BASIC_INFORMATION mbi;
VERIFY(VirtualQuery(&mbi, &mbi, sizeof(mbi)));
return uintptr_t(&mbi) - uintptr_t(mbi.AllocationBase);
}

这将与调用者中实际可用的内容略有不同,因为函数调用使用了一些(存储返回地址和任何保留的寄存器(。 您需要调查最终的保护页面是出现在同一个VirtualQuery结果中还是相邻的结果中。

但这是一般方法。