使用 pthread 无限堆栈大小

use*_*370 3 segmentation-fault stack pthreads

我的默认堆栈大小(根据 ulimit -s)是 8192 kB,所以当我尝试运行它时,自然会出现段错误下面的代码。此外,自然地,如果我执行'ulimit -s 9000',它可以正常工作。但是,当我执行 'ulimit -s unlimited' 时,代码再次出现段错误。任何想法这里发生了什么?

如果有用,我正在使用内核 4.19.0-6 和 gcc 版本 Debian 8.3.0-6 运行 Debian 10。

#include <iostream>
#include <unistd.h>
#include <cstdlib>

void* wait_exit(void*)
{
  char bob[8193*1024];
  return 0;
}

int main()
{
  pthread_t t_exit;
  int ret;
  
  if((ret = pthread_create(&t_exit,NULL,wait_exit,NULL)) !=0)
  {
    std::cout<<"Cannot create exit thread: "<<ret<<std::endl;
  }
  std::cout<<"Made thread"<<std::endl;
  sleep(5);
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

Voj*_*fny 5

因为对于线程“无限”在 x86_64 上只给你 2 MiB,请参见pthread_create 手册页

If the RLIMIT_STACK resource limit is set to "unlimited", a per-architecture value is used 
for the stack size.  Here is the value for a few architectures:

              ????????????????????????????????????
              ?Architecture ? Default stack size ?
              ????????????????????????????????????
              ?i386         ?               2 MB ?
              ????????????????????????????????????
              ?IA-64        ?              32 MB ?
              ????????????????????????????????????
              ?PowerPC      ?               4 MB ?
              ????????????????????????????????????
              ?S/390        ?               2 MB ?
              ????????????????????????????????????
              ?Sparc-32     ?               2 MB ?
              ????????????????????????????????????
              ?Sparc-64     ?               4 MB ?
              ????????????????????????????????????
              ?x86_64       ?               2 MB ?
              ????????????????????????????????????
Run Code Online (Sandbox Code Playgroud)

  • 谁会想到?这不是我的无限想法。无论如何,好的和简单的解决方案。谢谢。我想更安全的方法是使用 pthread_attr_setstacksize。 (2认同)
  • 谢谢。学习单词的新含义总是好的。像所有黄油肉馅饼一样(有棕榈油,或者没有盐水橄榄有海盐) (2认同)