【发布时间】:2021-03-16 07:46:09
【问题描述】:
我试图理解一个使用多线程和共享内存的程序。父线程调用如下函数,我不太明白它是如何工作的。
#define MAX_STACK_SIZE 16384 // 16KB of stack
/*!
* Writes to a 16 KB buffer on the stack. If we are using 4K pages for our
* stack, this will make sure that we won't have a page fault when the stack
* grows. Also mlock's all pages associated with the current process, which
* prevents the program from being swapped out. If we do run out of
* memory, the robot program will be killed by the OOM process killer (and
* leaves a log) instead of just becoming unresponsive.
*/
void HardwareBridge::prefaultStack() {
printf("[Init] Prefault stack...\n");
volatile char stack[MAX_STACK_SIZE];
memset(const_cast<char*>(stack), 0, MAX_STACK_SIZE);
if (mlockall(MCL_CURRENT | MCL_FUTURE) == -1) {
initError(
"mlockall failed. This is likely because you didn't run robot as "
"root.\n",
true);
}
}
//Parent Thread
void HardwareBridge::run(){
printf("[HardwareBridge] Init stack\n");
prefaultStack();
//printf("[HardwareBridge] Init scheduler\n"); // Commented because unrelated to current question
//setupScheduler();
// Calls multiple threads here
for(;;){
usleep(10000000);
}
}
谁能解释一下这个函数的目的是什么。根据评论,我可以理解它可以防止堆栈大小超过 16KB。但是,共享内存主要是在程序中使用new
关键字动态分配的。动态内存分配不是发生在堆中而不是堆栈中吗?该函数在这种情况下有何帮助。
【问题讨论】:
-
线程栈与共享内存完全无关。
标签: c++ memory-management shared-memory dynamic-memory-allocation