我正在使用 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/