線程與socket控制代碼

來源:互聯網
上載者:User
上午聽同事討論關於線程退出的時候是否需要關閉socket控制代碼的問題,之前都是在討論進程退出時,進程會釋放所佔有的所有資源,當然也包括socket 控制代碼資源,關於這點相信大部分人也相當的清楚。
關於線程退出時,socket控制代碼是否也會自動的關閉,我個人認為線程不會自動關閉socket控制代碼線上程退出時,因為線程是公用進程的資源,進程會自動釋放資源很顯然線程就不太可能釋放資源。為此我個人做了一個簡單的測試:
#include
#include
#includevoid *threadfunc(void* arg)
{
int nfd = socket(AF_INET, SOCK_STREAM, 0);
printf("fd=%d time=%d/n",nfd,time(NULL));
close(nfd);
}
int main()
{
pthread_t thid;
pthread_create(&thid,NULL,&threadfunc,NULL);1)
sleep(3);
printf("ddd/n");
pthread_create(&thid,NULL,&threadfunc,NULL);2)
sleep(3);
return 0;
}
在這裡,線程退出時,線程顯示的將socket關閉。1號線程擷取到的socket控制代碼為3(0,1,2前三個控制代碼預設的保留為輸入、輸出、錯誤輸出),2號線程擷取的socket據也為3;、
#include
#include
#include

void *threadfunc(void* arg)
{
int nfd = socket(AF_INET, SOCK_STREAM, 0);
printf("fd=%d time=%d/n",nfd,time(NULL));
}
int main()
{
pthread_t thid;
pthread_create(&thid,NULL,&threadfunc,NULL);3)
sleep(3);
printf("ddd/n");
pthread_create(&thid,NULL,&threadfunc,NULL);4)

sleep(3);
return 0;
}
這段代碼與上面的不同之處在於,線上程退出時,沒有關閉開啟的socket控制代碼,輸出的結果為:3、4。

為此,我們可以可以總結出,線上程退出時,線程並沒有自動關閉線程中的socket控制代碼。所以才會出現輸出結構為3、4。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.