that an application creates, so that system resources for the thread can be
released. (But note that the resources of all threads are freed when the
process terminates.)
也就是說:每個程序建立以後都應該調用pthread_join 或 pthread_detach 函數,隻有這樣線上程結束的時候資源(線程的描述資訊和stack)才能被釋放.
When a joinable thread terminates, its memory resources (thread descriptor and stack) are not deallocated until another thread performs pthread_join on it. Therefore, pthread_join must be called once for each joinable thread created to avoid memory leaks.
才知道如果在新線程裡面沒有調用pthread_join 或 pthread_detach會導緻記憶體洩漏, 如果你建立的線程越多,你的記憶體使用率就會越高, 直到你再無法建立線程,最終隻能結束程序。
解決方法有三個:
1. 線程裡面調用 pthread_detach(pthread_self()) 這個方法最簡單
2. 在建立線程的設定PTHREAD_CREATE_DETACHED屬性
3. 建立線程後用 pthread_join() 一直等待子線程結束。
下面是幾個簡單的例子
1. 調用 pthread_detach(pthread_self())
#include void *PrintHello(void) { pthread_detach(pthread_self()); int stack[1024 * 20] = {0,}; //sleep(1); long tid = 0; //printf(“Hello World! It’s me, thread #%ld!\n”, tid); //pthread_exit(NULL); } int main (int argc, char *argv[]) pthread_t pid; int rc; long t; while (1) { printf(“In main: creating thread %ld\n”, t); rc = pthread_create(&pid, NULL, PrintHello, NULL); if (rc){ printf(“ERROR; return code from pthread_create() is %d\n”, rc); //exit(-1); sleep(1); printf(” \n— main End —- \n”); pthread_exit(NULL);
//pthread_detach(pthread_self()); pthread_attr_t attr; pthread_t thread; pthread_attr_init (&attr); pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_DETACHED); rc = pthread_create(&pid, &attr, PrintHello, NULL); pthread_attr_destroy (&attr);
3. 建立線程後用 pthread_join() 一直等待子線程結束。
pthread_join(pid, NULL);
<a href="http://wifihack.net/blog/?attachment_id=447" target="_blank">測試代碼下載下傳</a>