我有一个跨平台多线程程序(Windows/Linux),在Linux上运行良好,在Windows上崩溃。在互联网上搜索给我一个想法,这是因为 stackoverflow:Linux 和 Windows 线程堆栈大小可能不同。那么如何检查每个线程(不仅仅是主线程)堆栈大小?写入堆栈直到程序崩溃(需要在windows和linux上都工作)?那么如何获得尺寸呢?
我在两个平台上了解线程堆栈大小的解决方案是一个简单的测试程序:创建线程,递归写入堆栈直到程序崩溃。是的,Windows 上为 1MB,Linux ARM 上为 8MB。
#include <stdio.h>
#include <stdlib.h>
#include <thread>
#include <iostream>
#if __linux__
#include <unistd.h>
#endif
#ifdef WINDOWS
#include <windows.h>
#endif
void mySleep(int sleepMs)
{
#if __linux__
usleep(sleepMs * 1000);
#endif
#ifdef WINDOWS
Sleep(sleepMs);
#endif
}
int counter {0};
void thread_func()
{
counter++;
std::cout << "func recursive step: " << counter << std::endl;
size_t sz = sizeof(unsigned long long);
std::cout << "size of ulonglong: " << sz << std::endl;
for(int i=0; i< 1000000; i++)
{
unsigned long long crush_array[5000]; //1 element = 8 byte (on windows)
for (auto &ar : crush_array)
ar = 18446744073709551614;
std::cout << "write " << sz*5000 <<"B array to stack" << std::endl;
std::cout << "thread stack size is less then " << (float)(sz*5000*counter)/(1024*1024) << " MB"<< std::endl << std::endl;
thread_func();
}
}
int main(void)
{
std::thread thread_obj = std::thread(thread_func);
thread_obj.detach();
mySleep(50000);
system("pause");
}
Windows 上的结果
Linux ARM 上的结果