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