pthread_create返回11解決方法
阿新 • • 發佈:2018-12-16
一直以為,程式建立執行緒,執行緒執行結束會自動清空資源
實則不然。
//pthread.c 錯誤demo示例 #include <stdio.h> #include <pthread.h> static int testcount = 0; static void *test_thread_handler() { testcount++; printf("%d\n",testcount); return 0; } int main( int argc, char *argv[] ) { int ret = 0; pthread_t test_tid; while(1) { usleep(10000); ret = pthread_create(&test_tid, NULL, test_thread_handler,NULL); if(ret != 0) { printf("Create handler error :%d!\t testcount:%d\n", ret, testcount); return -1; } } return 0; }
備註:pthread庫不是Linux系統預設的庫,連線時需要使用靜態庫libpthread.a,所以線上程函式在編譯時,需要連線庫函式
pthread_create()返回11的錯誤碼錶示Resource temporarily unavailable
資源暫時不可用,按理說執行緒return 0後資源應該自動釋放,同時我使用free檢視發現記憶體也是足夠的。
經過多方面查詢資料,得知linux執行緒執行和windows不同,pthread有兩種狀態joinable狀態和unjoinable狀態,預設的狀態是joinable。
如果執行緒是joinable狀態,當執行緒函式自己返回退出時或pthread_exit時都不會釋放執行緒所佔用堆疊和執行緒描述符(總計8K多),它的狀態類似於程序中的Zombie Process(殭屍程序)。只有當呼叫了pthread_join之後這些資源才會被釋放。
若是unjoinable狀態的執行緒,這些資源線上程函式退出時或pthread_exit時自動會被釋放。
但是呼叫pthread_join(pthread_id)後,如果該執行緒沒有執行結束,呼叫者會被阻塞,如果不需要阻塞的情況下,這時可以在子執行緒中加入程式碼
pthread_detach(pthread_self())
或者父執行緒呼叫
pthread_detach(test_tid)(非阻塞,可立即返回)
這將該子執行緒的狀態設定為detached,則該執行緒執行結束後會自動釋放所有資源。
最終程式如下:
//pthread.c 修復錯誤demo後示例 #include <stdio.h> #include <pthread.h> static int testcount = 0; static void *test_thread_handler() { pthread_detach(pthread_self()); testcount++; printf("%d\n",testcount); pthread_exit(0); return 0; } int main( int argc, char *argv[] ) { pthread_t test_tid; int ret = 0; while(1) { usleep(10000); ret = pthread_create(&test_tid, NULL, test_thread_handler,NULL); if(ret != 0) { printf("Create handler error :%d!\t testcount:%d\n", ret, testcount); return -1; } } return 0; }