pthread_join()在ios上失败

pthread_join() fail on ios

本文关键字:ios 失败 join pthread      更新时间:2023-10-16

我正在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);
}