I tried to subclass NSThread in order to operate a thread with some data. I want to simulate the join() in python, according to the doc:
join(): Wait until the thread terminates. This blocks the calling thread until the thread whose join() method is called terminates
So I think using performSelector: onThread: withObject: waitUntilDone:YES would be fine, but it does not work. It just do nothing and would not exit, running like forever.
This is my code:
@interface MyClass : NSThread
@property (strong, nonatomic) NSMutableArray *msgQueue;
@property (assign, nonatomic) BOOL stop;
@end
@implementation MyClass
-(id)init
{
self = [super init];
if (self) {
self.msgQueue = [NSMutableArray array];
self.stop = NO;
[self start];
return self;
}
return nil;
}
-(void)myRun
{
while (!self.stop) {
NSLock *arrayLock = [[NSLock alloc] init];
[arrayLock lock];
NSArray *message = [self.msgQueue firstObject];
[self.msgQueue removeObjectAtIndex:0];
[arrayLock unlock];
NSLog(@"%@", message);
if ([message[0] isEqualToString:@"terminate"]) {
self.stop = YES;
}
}
}
-(void)join
{
[self performSelector:@selector(myRun) onThread:self withObject:nil waitUntilDone:YES];
}
@end
int main(int argc, const char * argv[])
{
@autoreleasepool {
MyClass *a = [[MyClass alloc] init];
[a.msgQueue addObject:@[@"terminate",@"hello world"]];
//[a myRun]; // this line works so the myRun method should be good,
[a join]; // but I want this line work, and I have no idea what the problem is.
}
return 0;
}