C++线程的可用堆栈大小
Available stack size for C++ thread
我使用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
结果中还是相邻的结果中。
但这是一般方法。
相关文章:
- C++线程的可用堆栈大小
- 应该将线程分配给堆栈还是堆?
- 其他线程堆栈上的可用内存无效
- 访问其他线程堆栈变量如何在C++中工作?
- 为什么RCOUT和RPRINTF在多线程时会导致堆栈限制错误
- 如何获取 systemc 线程的堆栈大小
- 线程安全堆栈实现
- C 线程堆栈地址范围
- 如何使用pthreads在Solaris上增加C 线程堆栈的大小
- 线程的单独堆栈空间的重要性
- 如何使用 Win32 API 获取任何线程的堆栈大小和堆栈限制
- 将信号从Anthoter非过程中发送到线程,并没有发生记录堆栈
- 多线程时,您该怎么做才能停止堆栈空间
- 分叉式堆栈复制线程C++
- 繁忙时线程安全堆栈互斥被破坏
- 线程的调用堆栈中充满了相同的函数调用--curl_inet_ntop()
- 非阻塞线程安全堆栈
- 检测 Linux 上多线程C++应用程序中的堆栈溢出/覆盖
- 堆栈上的线程返回地址是什么
- 静态变量与堆栈变量:线程安全与堆栈大小