Monday, September 9, 2013

Strange NSThread issue in Objective C

I was trying to start a new thread, with the below code, in an OS X command line tool:

.h
NSThread *srvThread;

.mm
srvThread = [[NSThread alloc] initWithTarget:self selector:@selector(serverThreadFunc:)     object:@"Dummy"];

[srvThread start];
        
Everything was just proper in the selector also, but the new thread never started. I tried different possibilities, verified things over and again ... but the thread didn't start. 

Finally, tired, I was trying to just see the running status of the thread, with the below code:


        if ([srvThread isCancelled]) {
            NSLog(@"New Thread is in Cancelled State");
        } else if ([srvThread isExecuting]) {
            NSLog(@"New Thread is in Executing State");
        } else if ([srvThread isFinished]) {
            NSLog(@"New Thread is in Finished State");

        }

And what a surprise, the thread started working at once. The result I got was :

2013-09-10 10:19:31.896 AvConnectCli[1389:303] New Thread is in Executing State
2013-09-10 10:19:31.896 AvConnectCli[1389:2003] Started Server thread

I'm still checking what was the reason behind it for not starting the thread all these times. Maybe there should've a need for something for the Main thread to continue(there was nothing more in the main thread. It was end of the function). Will update if I can find proper reason for it. 

Again, I commented the thread state checking code and added this:

srvThread = [[NSThread alloc] initWithTarget:self selector:@selector(serverThreadFunc:) object:@"Dummy"];
[srvThread start];
        
for(int i=0;i<1000;i++){
     NSLog(@"%d",i);
}

//        if ([srvThread isCancelled]) {
//            NSLog(@"New Thread is in Cancelled State");
//        } else if ([srvThread isExecuting]) {
//            NSLog(@"New Thread is in Executing State");
//        } else if ([srvThread isFinished]) {
//            NSLog(@"New Thread is in Finished State");

//        }


Now also it's working just fine. The reason was because the main thread was ending soon after it spawned the new thread. The program was ending there. This could not be an issue which will be faced by many, but for starters, who try to just try out multithreading in Objective C, this can cause some confusion. 

No comments:

Post a Comment