設置並查看pthread創建線程時傳入參數中堆棧大小值


轉載:https://www.jianshu.com/p/9aa67b22fec3
眾所周知的pthread_create的函數原型如下:

#include <pthread.h>
int pthread_create(
    pthread_t *restrict tidp,             //新創建的線程ID指向的內存單元。
    const pthread_attr_t *restrict attr,  //線程屬性,默認為NULL
    void *(*start_rtn)(void *),           //新創建的線程從start_rtn函數的地址開始運行
    void *restrict arg                    //默認為NULL。若上述函數需要參數,將參數放入結構中並將地址作為arg傳入。
  );

其中設置堆棧大小就靠attr參數,測試代碼如下:

#include <iostream>
#include <limits.h>
#include <pthread.h>
#include "error.h"
using namespace std;
int main(){
    pthread_t thread;
    size_t stacksize;
    pthread_attr_t thread_attr;
    int ret;
    pthread_attr_init(&thread_attr);
    int new_size = 20480;
    ret =  pthread_attr_getstacksize(&thread_attr,&stacksize);
    if(ret != 0){
        cout << "emError" << endl;
        return -1;
    }
    cout << "stacksize=" << stacksize << endl;
    cout << PTHREAD_STACK_MIN << endl;
    ret = pthread_attr_setstacksize(&thread_attr,new_size);
    if(ret != 0){
        return -1;
    }
    ret = pthread_attr_getstacksize(&thread_attr,&stacksize);
    if(ret != 0){
        cout << "emError" << endl;
        return -1;
    }
    cout << "after set stacksize=" << stacksize << endl;
    ret = pthread_attr_destroy(&thread_attr);
    if(ret != 0)
       return -1;
    return 0;
}

編譯命令:

g++ main.cpp -o main -lpthread

運行結果如下:

[root@lh test]#./main 
stacksize=8388608
16384
after set stacksize=20480

即:
系統的默認值:8388608
最小值:16384


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM