C函數之pthread_create()使用

用pthread_create方法創建的線程,默認是非detached的,也就是說當線程退出時它所佔用的系統資源並沒有完全真正的釋放,也沒有真正終止,就會出現內存泄漏

有個案子,按下button的時候我們就啓動線程來播放一段聲音,如果不停的按門鈴發現一段時間之後就無法播放聲音了,查下來發現創建線程失敗error是cannot allocate memory。

 

以下提出有3種方法可以避免這個問題:

1. 在pthread_create創建線程時設置detached的屬性,這樣線程結束時會立即釋放所用資源:

pthread_t thread;

pthread_attr_t attr;

pthread_attr_init( &attr );

pthread_attr_setdetachstate(&attr,1);

pthread_create(&thread, &attr, run, 0);

2. 在線程結束之前手動執行detached操作:

void run() {

pthread_detach(pthread_self());

}

int main(){

pthread_t thread;

pthread_create(&thread, NULL, run, 0);

//......

return 0;

}

3. 線程使用pthread_join,這樣當pthread_join返回時,線程會釋放資源:

int main(){

pthread_t thread;

pthread_create(&thread, NULL, run, 0);

//......

pthread_join(thread,NULL);

return 0;

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章