簡體   English   中英

pthread_join()在iOS上失敗

[英]pthread_join() fail on ios

我正在IOS上進行多線程項目。 在我的項目中,pthread連接有時會失敗。

pthread_join(thread_id, NULL) == 0

注意:這僅在IOS上發生,並且是隨機的。 聯接操作失敗的原因可能是什么。

手冊頁說:

錯誤如果出現以下情況,pthread_join()將失敗:

 [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.

我遇到了同樣的問題,並且找到了一個簡單的解決方案:不要調用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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM