我正在做一个关于 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);
}