3 回答
TA貢獻1845條經驗 獲得超8個贊
通常,您可以main()在調用任何其他函數之前,例如在的開始處及早設置堆棧大小。通常,邏輯為:
調用getrlimit以獲取當前堆棧大小
如果當前大小<所需的堆棧大小,則
調用setrlimit以將堆棧大小增加到所需大小
在C語言中,可能會這樣編碼:
#include <sys/resource.h>
#include <stdio.h>
int main (int argc, char **argv)
{
const rlim_t kStackSize = 64L * 1024L * 1024L; // min stack size = 64 Mb
struct rlimit rl;
int result;
result = getrlimit(RLIMIT_STACK, &rl);
if (result == 0)
{
if (rl.rlim_cur < kStackSize)
{
rl.rlim_cur = kStackSize;
result = setrlimit(RLIMIT_STACK, &rl);
if (result != 0)
{
fprintf(stderr, "setrlimit returned result = %d\n", result);
}
}
}
// ...
return 0;
}
TA貢獻1802條經驗 獲得超5個贊
要超出setrlimit中的硬限制(在OSX上默認只有64MB),請使用具有選擇的堆棧大小的pthreads創建一個新線程。這是一個C代碼段:
// Call function f with a 256MB stack.
static int bigstack(void *(*f)(void *), void* userdata) {
pthread_t thread;
pthread_attr_t attr;
// allocate a 256MB region for the stack.
size_t stacksize = 256*1024*1024;
pthread_attr_init(&attr);
pthread_attr_setstacksize(&attr, stacksize);
int rc = pthread_create(&thread, &attr, f, userdata);
if (rc){
printf("ERROR: return code from pthread_create() is %d\n", rc);
return 0;
}
pthread_join(thread, NULL);
return 1;
}
- 3 回答
- 0 關注
- 523 瀏覽
添加回答
舉報
