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

时间:2018-03-12 10:11:26

标签: ios objective-c 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);
    }
}

1 个答案:

答案 0 :(得分:1)

像这样的实时锁定在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];
}