Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/jsp/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ubuntu 如何在PThread退出后回收内存?_Ubuntu_Pthreads - Fatal编程技术网

Ubuntu 如何在PThread退出后回收内存?

Ubuntu 如何在PThread退出后回收内存?,ubuntu,pthreads,Ubuntu,Pthreads,我正在Ubuntu中使用pthread\u create函数创建一个线程。我通过top命令观察到,一旦创建了线程,虚拟内存就会增加,但即使在线程退出之后,内存也不会减少。我甚至使用了pthread\u detach()[根据pthread\u detach手册,它会自动释放在创建过程中获取的所有资源],但仍然得到了相同的结果。请查找下面的示例代码: size_t const thread_no = 1; char mess[] = "This is a test"; void *messag

我正在Ubuntu中使用
pthread\u create
函数创建一个线程。我通过top命令观察到,一旦创建了线程,虚拟内存就会增加,但即使在线程退出之后,内存也不会减少。我甚至使用了
pthread\u detach()
[根据
pthread\u 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);
}
size\t const thread\u no=1;
char mess[]=“这是一个测试”;
void*消息打印(void*ptr){
整数误差=0;
char*msg;
/*拆线*/
error=pthread_detach(pthread_self());
/*处理错误(如果有)*/
printf(“线程:这是消息%s\n”,mess);
}
内部主(空){
整数误差=0;
尺寸i=0;
/*创建一个线程池*/
pthread_t thr[线程编号];
pthread_attr_t attr;
pthread_attr_init(&attr);
error=pthread\u attr\u setdetachstate(&attr,pthread\u CREATE\u JOINABLE);
对于(i=0;i
当操作系统实际回收资源时,这实际上取决于操作系统。你可能马上就能看到效果,也可能看不到。如果您想生成另一个线程(或不想),操作系统可能会保留该资源。它可能会一直持有它,直到它真的被其他东西所需要


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

我也有同样的问题,我只是通过设置detach属性解决了这个问题

pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); 
我希望这也能解决你的问题