c++ - 为什么无法创建堆栈大小小于默认大小的线程?

标签 c++ multithreading pthreads

我已经编写了一个小程序来创建线程并更改它们的默认堆栈大小,但在我的例子中。当我在更改属性后打印 stacksize 时,我仍然将 stacksize 显示为默认堆栈大小。

        # include<iostream>
        # include<pthread.h>
        # include<stdio.h>
        # define size 10
        using namespace std;
        pthread_attr_t attr;

        void* sum(void * threadid)
        {
          static int sum =0;
          sum=sum+5;
          long id=(long)threadid;
          size_t mystacksize;
          pthread_attr_getstacksize(&attr,&mystacksize);
          cout << " stack size  "<< mystacksize <<endl;
        }
        int main()
        {
         int rc;
         long t=0;
         pthread_t threads[5];  //number of different thread to br creatd
         size_t stacksize;
         pthread_attr_init(&attr);
         pthread_attr_getstacksize(&attr,&stacksize);   //gets the default stack size 
                                                        //allocated for thread
         cout <<" Default stack size is : " << stacksize <<endl; 
         stacksize=size;
         pthread_attr_setstacksize(&attr,stacksize);  //sets a new stacksize for thread
           for(t=0;t<5;t++)
            {
              rc=pthread_create(&threads[t],&attr,sum,(void*)t);
              if(rc)
              cout << "thread creation failed with id : " << t <<endl;
            }
         pthread_exit(NULL);
        return 0;
        }

输出是:-

           Default stack size is : 8388608
           stack size  : 8388608
           stack size  : 8388608
           stack size  : 8388608
           stack size  : 8388608
           stack size  : 8388608

另请注意,如果我尝试将 stacksize 增加到大于 default size,我就能成功地做到这一点。

最佳答案

期望能够使用十个字节的堆栈大小真是太疯狂了。

您是否阅读了pthread_attr_setstacksize 手册页?您是否检查了调用 pthread_attr_setstacksize 的返回值?

在我的系统 (GNU/Linux) 上,手册页说:

   pthread_attr_setstacksize() can fail with the following error:

   EINVAL The stack size is less than PTHREAD_STACK_MIN (16384) bytes.

关于c++ - 为什么无法创建堆栈大小小于默认大小的线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10642233/

相关文章:

c++ - 将类分离到它们自己的定义和实现文件中,并将 main 放在它自己的文件中

c++ - C++中 "~"(波浪号)符号的含义?

C#多线程并发算法

c++ - 请帮我检查有关 Windows Embedded 的 Silverlight 中数据绑定(bind)的代码

c++ - 在 main 中使用指向变量的指针的 Pthread 段错误

c++ - pthread 并行运行类实例的方法

c - 多次互斥锁定

c++ - Xvideos 随时随地在线

c++ - 弹性和 Bison : how to recognize an array

Java:奇怪的死锁