Linux下创建一个线程占用多少内存

在前面的博客进程分配资源中,我们了解到,在32位平台下,系统会给一个进程分配4G的虚拟内存供进程使用。

因此,我们知道,一个进程被创建时将被分配有4G的虚拟内存。事实上,并不是每次都会用完这4G内存的,下面的例子可以看到。

#include <stdio.h>
#include <unistd.h>

int main(){
    while(1){
        sleep(1);
    }
    return 0;
}

在我们上面的程序中,我们只在main函数写了一个死循环,以便我们来关注该进程占有的内存大小 

注意上图的红框部分,这是ps命令列出来的VSZ选项,表示进程占用的虚拟内存,于是我们可以看到,主线程main占用的虚拟内存是4164差不多就是6M。系统分配给了我们4G的虚拟内存,但实际上我们只用了6M的虚拟内存(这就可以验证我们上面说并不会每次用完4G的虚拟内存)。

我们知道了一个进程被创建时分配的内存,那么一个线程创建时会分配多少内存呢?

我们通过在上面的代码中创建一个线程来验证

#include <stdio.h>
#include <unistd.h>
#include <pthread.h>

void* thread(void* arg){
    while(1){
        sleep(1);
    }
}

int main(){
    pthread_t thread1;
    if(pthread_create(&thread1,NULL,thread,NULL) < 0)
        perror("pthread_create");
    while(1){
        sleep(1);
    }
    return 0;
}

一个主线程main+一个线程占有的虚拟内存是16700K,16700 - 6324 = 10376K,差不多就是10M。为什么我们多创建一个线程就会多出来10M的空间呢?这里我们可以想到,进程中的所有线程是共享进程的地址空间的,但是系统会为每个线程分配独立的调用栈,也就说每个线程都会有一个自己的调用栈。在我们当前的机器下,我们设置的调用栈的大小就是10M。

[pigff@izbp13yd4r85qvk53t04mbz ~]$ ulimit -s
10240

于是我们就想到,这个多出来的10M虚拟内存,是不是就是新线程的调用栈的大小呢?

我们再创建一个线程看看

#include <stdio.h>
#include <unistd.h>
#include <pthread.h>

void* thread_entry1(void* arg){
    while(1){
        sleep(1);
    }
}

void* thread_entry2(void* arg){
    while(1){
        sleep(1);
    }
}

int main(){
    pthread_t thread1;
    pthread_t thread2;
    if(pthread_create(&thread1,NULL,thread_entry1,NULL) < 0)
        perror("pthread_create");
    if(pthread_create(&thread2,NULL,thread_entry2,NULL) < 0)
        perror("pthread_create");
    while(1){
        sleep(1);
    }
    return 0;
}

26944 - 16700 = 10244,差不多也是10M。

所以我们基本可以推断,创建一个线程,会给这个内存分配10M的虚拟内存,也就是说,创建一个线程的消耗是10M内存。另外,这其实就是调用栈的大小,可以设置的,也就是说,创建一个线程的消耗其实就是调用栈的大小

猜你喜欢

转载自blog.csdn.net/lvyibin890/article/details/82254697
今日推荐