David Dai
David Dai

Reputation: 1145

NSThread Programming issues

I am currently learning IOS Threading programming... I encountered an issue:

Here comes my code, please kindly have a look:

int main(int argc, const char * argv[])
{
    @autoreleasepool {
        NSThread *t1 = [[NSThread alloc]initWithTarget:[MyThread class] selector:@selector(myMethod:) object:Nil];
        [t1 start];
    }
    return 0;
}

#import "MyThread.h"

@implementation MyThread

+ (void)myMethod:(id)param
{
    @autoreleasepool {
        NSLog(@"called...");
    }
}

@end

However, when I ran my program, though there was no error, no message was printed on the console. It seems like myMethod was not executed. I wonder if anyone could give me some suggestions. It has already driven me crazy.

Many thanks in advance.

Upvotes: 0

Views: 313

Answers (2)

CRD
CRD

Reputation: 53000

Your application is terminating before the thread has executed the NSLog.

NSThread creates a detached thread, see Apple's Thread Programming Guide, from which comes:

Important: At application exit time, detached threads can be terminated immediately but joinable threads cannot. Each joinable thread must be joined before the process is allowed to exit. Joinable threads may therefore be preferable in cases where the thread is doing critical work that should not be interrupted, such as saving data to disk.

To create a joinable thread, and hence be able to block your main thread until all joinable threads have finished, you use pthread - covered in the above Guide.

The Java thread model is similar, but uses slightly different terminology. By default a Java thread is joinable and the Java application will continue to execute until all such threads have terminated. A Java thread can be converted to a daemon thread, which is automatically terminated on application exit as with NSThread threads.

Upvotes: 1

Harry
Harry

Reputation: 3106

The main thread of your application is exiting before your other thread has a chance to process anything.

It will work if you add in a simple sleep(1000) statement anywhere before the return 0 statement in your main method.

Upvotes: 1

Related Questions