我使用pthread_create
函數在Ubuntu中創建線程。我已經通過頂層命令觀察到,一旦創建線程,虛擬內存就會增加,但即使線程退出後,內存也不會減少。我甚至使用了pthread_detach()
[按照pthread_detach
手冊,它會自動釋放它在創建過程中獲得的所有資源],但仍得到相同的結果。請找到下面的示例代碼:如何在PThread退出後回收內存?
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);
}