NSThread的下一个自定义联接实现会有多糟糕



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];
}

最新更新