标签搜索

关于线程栈大小设置实验

anker
2021-06-26 / 0 评论 / 29 阅读 / 正在检测是否收录...

每个线程的创建都是有消耗的。这里关注线程栈大小和设置。在Redis的IO线程中也是有设置线程栈为4MB大小的。另外验证的ulimit -s设置时,只能设置为比当前更小,不能扩大。

//anker<lichengman2006@gmail.com> @2021-06-20T18:12:11
//gcc thread_stack_size.c -o thread_stack_size -D_GNU_SOURCE -lpthread
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

size_t get_current_thread_stacksize(){
    pthread_attr_t attr;
    size_t stacksize;
    //pthread_attr_init(&attr);
    pthread_getattr_np(pthread_self(), &attr);
    int err = pthread_attr_getstacksize(&attr,&stacksize);

    if(err != 0){
        perror("cannot get thread stack size\n");
        exit(err);
    }
    pthread_attr_destroy(&attr);
    return stacksize;
}

void *thread_entry(void *arg) {
    char * msg = (char *)arg;
    size_t stacksize = get_current_thread_stacksize();
    printf("get %s stack size(bytes):%ld\n", msg, stacksize);
}

int main(int argc, char *argv[]){
    if(argc != 2){
        printf("usage:"
               "thread_stack_size $sizInMB\n"
                );
        exit(1);
    }

    size_t main_stacksize = get_current_thread_stacksize();
    printf("get main thread stack size(bytes):%ld\n", main_stacksize);

    pthread_t threadId;
    if (pthread_create(&threadId, NULL, thread_entry, "first thread") != 0) {
        perror("cannot create sub thread");
        exit(errno);
    }
    pthread_join(threadId, NULL);

    pthread_attr_t attr;
    pthread_attr_init(&attr);
    if ( 0 != pthread_attr_setstacksize(&attr, 1024*1024*atoi(argv[1]))){
    //if ( 0 != pthread_attr_setstacksize(&attr, 1024*1024*10)){
        perror("set stack size failed.");
        exit(errno);
    }
    pthread_t threadId2;
    if (pthread_create(&threadId2, &attr, thread_entry, "second thread") != 0) {
        printf("cannot create sub thread");
        exit(errno);
    }

    pthread_attr_destroy(&attr);
    pthread_join(threadId2, NULL);
    return 0;
}

pthread_attr_setstacksize函数说明提到:
The stack size attribute determines the minimum size (in bytes) that will be allocated for threads created using the thread attributes object attr.
他设置的是栈大小的最小值,另外系统也是有限制栈的16KB最小值PTHREAD_STACK_MIN (16384) bytes.

> ulimit -s 4096

> ./thread_stack_size 5
get main thread stack size(bytes):4194304
get first thread stack size(bytes):4194304
get second thread stack size(bytes):5242880

> ./thread_stack_size 3
get main thread stack size(bytes):4190208
get first thread stack size(bytes):4194304
get second thread stack size(bytes):4194304

留意以下事实:

  • 子线程和主线程的栈大小是不一致的。
  • pthread_attr_setstacksize是设置比ulimit还小的值,系统会自动采用最大的最小值。更详细的策略可以参考
    glibc的allocatestack.c中的allocate_stack函数,其中有对齐等考虑因素。
0

评论 (0)

取消