新聞中心
線程是程序中運(yùn)行的任何程序的基礎(chǔ),是通過(guò)分配給操作系統(tǒng)的代碼來(lái)創(chuàng)建,管理和控制程序本質(zhì)上是不同的部分。在使用線程時(shí),應(yīng)特別注意如何正確關(guān)閉線程。只有正確關(guān)閉線程,才能保證系統(tǒng)能正確運(yùn)行。

要正確關(guān)閉linux下的線程,建議使用pthread_join()函數(shù)或pthread_detach()函數(shù)。
首先介紹pthread_join()函數(shù),它是一個(gè)阻塞性函數(shù),等待線程結(jié)束,當(dāng)每個(gè)線程在創(chuàng)建的時(shí)候,都會(huì)返回一個(gè)引用線程的句柄;可以拿著這個(gè)句柄來(lái)調(diào)用pthread_join(),來(lái)等待指定的線程結(jié)束。下面是一個(gè)示例代碼:
“`c
#include
…
pthread_t a_thread;
int ret =pthread_create(&a_thread, NULL, thread_function, parameter);
…
ret = pthread_join(a_thread, NULL);
if( ret!= 0)
{
fprintf(stderr, “pthread_join error: %s\n”, strerror(ret));
}
此外,pthread_detach()函數(shù)也可以很好的用來(lái)關(guān)閉線程。它將線程脫離主線程,不過(guò)他也有對(duì)應(yīng)的句柄,當(dāng)線程脫離之后,它會(huì)自動(dòng)回收資源,不需要進(jìn)程主動(dòng)的回收資源:
```c
#include
...
pthread_t a_thread;
int ret =pthread_create(&a_thread, NULL, thread_function, parameter);
...
ret = pthread_detach(a_thread);
if (ret != 0)
{
fprintf(stderr, "pthread_detach error: %s\n", strerror(ret));
}
總結(jié)來(lái)說(shuō),Linux下有兩種正確的線程關(guān)閉方法,一種是pthread_join()函數(shù),它是一個(gè)阻塞函數(shù),需要等待指定的線程結(jié)束;另一個(gè)是pthread_detach()函數(shù),它將線程脫離主線程,讓操作系統(tǒng)自動(dòng)回收資源,無(wú)需進(jìn)程主動(dòng)的去控制回收資源。開發(fā)者可選擇使用哪一種的依據(jù)自身的需求來(lái)決定。
成都創(chuàng)新互聯(lián)科技有限公司,經(jīng)過(guò)多年的不懈努力,公司現(xiàn)已經(jīng)成為一家專業(yè)從事IT產(chǎn)品開發(fā)和營(yíng)銷公司。廣泛應(yīng)用于計(jì)算機(jī)網(wǎng)絡(luò)、設(shè)計(jì)、SEO優(yōu)化、關(guān)鍵詞排名等多種行業(yè)!
網(wǎng)站欄目:Linux下關(guān)閉線程的正確方法(linux關(guān)閉線程)
分享URL:http://m.fisionsoft.com.cn/article/dpehjeo.html


咨詢
建站咨詢
