2013-07-15 91 views
1

我正在開發IOS上的多線程項目。 在我的項目中,pthread加入失敗了。pthread_join()在IOS上失敗

pthread_join(thread_id, NULL) == 0 

注意:這僅僅是發生在IOS,它是隨機的。 失敗連接操作的原因可能是什麼。

+1

和你的代碼是什麼? – hetepeperfan

+1

由於你的問題非常廣泛(沒有代碼,沒有細節),答案也必須廣泛:**原因是你在某個地方某個時候犯了一個錯誤。**(對於更詳細的答案,提供更多詳細信息你的問題,例如[SSCCE](http://sscce.org)和你得到的錯誤信息。 –

+0

ios在失敗時不返回錯誤代碼? – PlasmaHH

回答

1

手冊頁說:

[EDEADLK]   A deadlock was detected or the value of thread speci- 
        fies the calling thread. 

[EINVAL]   The implementation has detected that the value speci- 
        fied by thread does not refer to a joinable thread. 

[ESRCH]   No thread could be found corresponding to that speci- 
        fied by the given thread ID, thread. 
0

我有同樣的問題,並發現了一個簡單的解決方案:如果

錯誤 在pthread_join()將失敗不要調用pthread_detach()。根據文檔,pthread_detach將腳踏板移動到不能再連接的狀態,所以pthread_join在EINVAL中失敗。

的源代碼可能是這個樣子:

pthread_t  thread; 
pthread_attr_t threadAttr; 

bool run = true; 
void *runFunc(void *p) { 
    while (run) { ... } 
} 

- (void)testThread { 
    int status = pthread_attr_init(&threadAttr); 
    NSLog(@"pthread_attr_init status: %d", status); 
    status = pthread_attr_setdetachstate(&threadAttr, PTHREAD_CREATE_JOINABLE); 
    NSLog(@"pthread_attr_setdetachstate status: %d", status); 
    status = pthread_create(&thread, &threadAttr, &runFunc, (__bridge void *)self); 
    NSLog(@"pthread_create status: %d", status); 
    /* let the thread run ... */ 
    run = false; 
    status = pthread_join(thread, NULL); 
    NSLog(@"pthread_join status: %d == %d, ?", status, EINVAL); 
}