NSThread 的下一个自定义连接实现有多糟糕?

How bad would be next custom join implementation for 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];
}