You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

pthread_create实际内存占用探究:Ubuntu下Valgrind测试差异解析

pthread_create实际内存占用分析(Ubuntu 24.04)

测试场景

在Ubuntu 24.04上编写了如下多线程测试程序,编译为可执行文件thread:

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

void *thread(void *arg) {
  printf("thread() entered with argument '%s'\n", arg);
  pthread_exit((void*)"success");
}

int main() {
  pthread_t thid;
  void *ret;

  if (pthread_create(&thid, NULL, thread, (void*)"thread 1") != 0) {
    perror("pthread_create() error");
    exit(1);
  }

  if (pthread_join(thid, &ret) != 0) {
    perror("pthread_join() error");
    exit(3);
  }

  printf("thread exited with '%s'\n", ret);
}

两次Valgrind测试结果

  1. 执行普通Massif命令:

    valgrind --tool=massif ./thread
    

    报告显示pthread_create仅占用272B:

    ->04.78% (272B) 0x40145AB: _dl_allocate_tls (in /usr/lib/x86_64-linux-gnu/ld-linux-x86-64.so.2)
    | ->04.78% (272B) 0x48F4606: pthread_create (in /usr/lib/x86_64-linux-gnu/libc.so.6)
    |   ->04.78% (272B) 0x10927F: main (in /home/sameer/profile/thread)
    
  2. 启用--pages-as-heap=yes参数执行:

    valgrind --tool=massif --pages-as-heap=yes ./thread
    

    报告显示内存占用约8MB:

    ->05.70% (8,392,704B) 0x48E3526: pthread_create (in /usr/lib/x86_64-linux-gnu/libc.so.6)
    |   ->05.70% (8,392,704B) 0x10927F: main (in /home/sameer/profile/thread)
    

问题解答

是的,8MB可以认为是Ubuntu 24.04系统上单线程创建的全部典型内存开销(包含系统层面的所有内存占用),具体原因如下:

两种Massif模式的统计差异

  • 普通模式:
    Massif默认仅追踪通过malloc/calloc/free等标准堆分配函数管理的内存。而pthread_create创建线程时,核心内存开销(如线程栈、线程本地存储TLS的主要区域)是通过mmap系统调用分配的匿名内存页,这类内存不在默认统计范围内。你看到的272B只是线程创建过程中少量的堆内存开销(比如TLS的控制结构)。

  • --pages-as-heap=yes模式:
    该参数会让Massif将所有通过mmap分配的内存页都纳入堆内存统计,这就完整覆盖了线程创建的全部内存开销——其中占比最大的是Linux默认的8MB线程栈(可通过ulimit -s查看,Ubuntu 24.04默认栈大小为8192KB),再加上TLS等其他小量内存,总和约为8MB。

结论

8MB就是pthread_create创建线程的真实全部内存占用,属于Ubuntu 24.04上单线程创建的典型系统开销值。

内容的提问来源于stack exchange,提问作者Sameer Mahajan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 07:47:34