[英]What happens to the pthread when it exits the function
假設我在while
循環中使用pthread_create(pthread_t *thread, pthread_attr_t *attr, void *(*fun) (void *), void *arg)
,一旦線程完成函數fun()
后會發生什么?如果我調用int pthread_detach(pthread_t thread)
還是只有主線程停留在循環中,它也會與主線程陷入循環中?
例:
pthread_t t[NTHREADS];
int i = -1;
while(1){
//do something
++i;
pthread_create(&t[i], NULL, fun, (void *)i);
pthread_detach(t[i]);
//main thread goes on, created one detaches when finished
}
我想做的是一個多客戶端服務器,其中每個線程都為其自己的客戶端服務,存在NTHREADS
並且當某些線程完成fun()
或更確切地說是為其客戶端提供服務時,則t[]
的插槽打開,可以創建另一個線程(其他客戶端可以連接),如果之前已滿。
從啟動函數返回的pthread等同於調用pthread_exit
線程。 如果線程是分離的,則它不再存在。
規范說,從線程函數返回等同於調用pthread_exit
,線程函數的返回值可用於pthread_join
(前提是您沒有分離線程)。
通常,這是通過讓pthread_create
創建一個線程開始執行固定的(libc)“線程入口函數”來實現的。 此入口函數調用您的函數,然后調用pthread_exit
(在完成所有相關的清除之后)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.