Cause NSThread
can't be joinable I tried next method, it seems works ok, but is still very bad solution or good enough?
// 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);
}
}
A live lock like this is a bad idea on an iPhone, because it eats battery and CPU without doing anything, even though calling sleep(0) might give it a little bit of rest.
You could use NSCondition to implement joining. The idea is that the parent thread will wait on the NSCondition, and the worker thread would signal on that condition when it finishes:
- (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];
}