因为 NSThread
无法连接 我尝试了下一个方法,它似乎工作正常,但仍然是非常糟糕的解决方案还是足够好?
// init thread
NSThread *mythread = [[NSThread alloc] initWithTarget:self selector:@selector(runThread:) object: nil];
// start thread
mythread.start;
// JOIN NSThread custom implementation
// wait until thread will finish execution
if (mythread.isExecuting) {
while(mythread.isExecuting) {
sleep(0);
}
} else if (!mythread.isCancelled && !mythread.isFinished) {
while(!mythread.isExecuting) {
sleep(0);
}
while(mythread.isExecuting) {
sleep(0);
}
}
最佳答案
像这样的活锁在 iPhone 上不是一个好主意,因为它会在不做任何事情的情况下消耗电池和 CPU,即使调用 sleep(0) 可能会让它稍微休息一下。
你可以使用 NSCondition实现加入。这个想法是父线程将等待 NSCondition,工作线程将在完成时发出信号:
- (void)main1 {
// thread 1: start up
_joinCond = [NSCondition new];
[mythread start];
// thread 1: join, i.e. wait until thread 2 finishes
[_joinCond lock];
[_joinCond wait];
[_joinCond unlock];
}
- (void)main2 {
// thread 2 (mythread):
// ... work, work, work ...
// now we're done, notify:
[_joinCond lock];
[_joinCond signal];
[_joinCond unlock];
}
关于ios - NSThread 的下一个自定义连接实现有多糟糕?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49232639/