|
線程終止: 1.start_routine回調函數執行return; 2.線程自身調用pthread_exit(); 3.其他線程調用pthread_cancel(ID)將此進程終止; 任意線程調用exit()使整個進程退出。 線程回收:線程默認joinable狀態,終止后需使用pthread_join回收資源;將子線程使用pthread_detach從主線程分離后處于unjoinable狀態,系統等線程退出后自動回收資源。 常用的 函數調用如下: pthread_exit():結束本線程 #include void pthread_exit(void *retval); 參數含義: retval:線程返回值,其他線程調用pthread_join()接收。 pthread_cancel():向指定線程發出取消請求,使用pthread_join回收, #include int pthread_cancel(pthread_t thread); 參數含義: thread:要終止的線程ID; 返回值:執行成功返回0,成功不一定會讓指定線程終止;執行失敗返回錯誤號, pthread_join():等待線程終止回收資源,獲取返回值retval, #include int pthread_join(pthread_t thread, void **retval); 參數含義: thread:線程 ID。 retval:存放回收線程的返回值。 返回值:成功返回0,失敗返回錯誤號。 pthread_detach():分離線程,線程終止后系統自動清理,分離后不能再使用join獲取狀態, #include int pthread_detach(pthread_t thread); 參數含義:要分離的線程 ID。 返回值:成功返回0,失敗返回錯誤號。 本章代碼在thread/目錄下,實驗1:路徑為:11_Linux系統開發進階\Linux系統編程_章節使用資料。 使用pthread_cancel讓線程退出,pthread_join回收,代碼在cancel.c:
編譯:gcc cancel.c -o cancel -lpthread,運行結果:
使用pthread_exit讓線程退出,pthread_join回收線程資源,代碼在/thread/exit/目錄下, 線程依次使用pthread_exit退出,然后pthread_join依次回收線程,main.c:
編譯運行,可以看到線程按順序依次退出并打印pthread_exit的返回值:
實驗三: 使用pthread_detach()設置線程分離,pthread_exit()退出后,系統自動回收,最后調用pthread_join()發現報錯,說明線程分離后線程自動釋放。 實驗代碼在detach.c:路徑為:11_Linux系統開發進階\Linux系統編程_章節使用資料。
編譯,gcc -o detach detach.c -lpthread,運行結果如下,發現使用pthread_join()報錯:
|