2011-11-17 16 views
2

我使用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); 
} 

回答

2

當操作系統實際回收資源時,它確實取決於操作系統。您可能會立即看到效果,也可能看不到效果。如果你想產生另一個線程(或不是),OS可以保留資源。它可能會持有它,直到它真的需要其他東西。

即使您已經「發佈」它,操作系統可能不需要立即回收它。

0

我有同樣的問題,我只是通過設置分離的問題解決了屬性

pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); 

我希望可以解決您的了。