ubuntu - PThread 退出后如何回收内存?

标签 ubuntu pthreads

我正在使用 pthread_create 在 Ubuntu 中创建一个线程功能。我通过 top 命令观察到,一旦创建线程,虚拟内存就会增加,但即使在线程退出后,内存也不会减少。我什至用过pthread_detach() [根据 pthread_detach手动,它会自动释放它在创建过程中获得的所有资源],但仍然得到相同的结果。请在下面找到示例代码:

size_t  const thread_no = 1;
char mess[] = "This is a test";

void *message_print(void *ptr){
  int error = 0;
  char *msg;

  /* Detach the thread */
  error = pthread_detach(pthread_self());
  /* Handle error if any */

  printf("THREAD: This is the Message %s\n", mess);
}

int main(void) {
  int error = 0;
  size_t i = 0;
  /* Create a pool of threads */
  pthread_t thr[thread_no];
  pthread_attr_t attr;

  pthread_attr_init(&attr);
  error = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);

  for(i = 0; i < thread_no; i++) {
    error = pthread_create( &(thr[i]), &attr, message_print, (void *) mess);
    /* Handle error */
  }
  printf("MAIN: Thread Message: %s\n", mess);
  while(1);
}

最佳答案

当操作系统实际回收资源时,这实际上取决于操作系统。您可能会或可能不会立即看到效果。如果您想要(或不)产生另一个线程,操作系统可能会保留资源。它可能会一直持有它,直到它真正需要其他东西为止。

即使您已“释放”它,操作系统也可能不需要立即实际回收它。

关于ubuntu - PThread 退出后如何回收内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8170734/

相关文章:

c++ - ZED SDK 加载共享库时出错 : libGLEW. so.1.13:无法打开共享对象文件:没有这样的文件或目录

C - 使用互斥锁和线程的段错误

c - 从另一个线程访问主线程的局部变量

php - Apache2 优雅加载不同的 php.ini

memory - 程序刚刚填满了我的内存并开始在 Xubuntu 中填满交换空间

ubuntu - IntelliJ Idea 仅在主显示屏上打开主菜单、上下文菜单和自动完成

node.js - Windows > Vagrant > nodejs 看不到本地包

c - 不停止 gdb 中的所有线程

c++ - 生产者、消费者和我可爱的僵局

linux - 与 pthreads 和 stdc++ 的静态链接?