2013-07-15 47 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); 
}