0

I explicitly created a worker thread with NSThread class.

NSThread *workerThread = [[NSThread alloc] initWithTarget:self
                                                    selector:@selector(doWork)
                                                      object:nil];
[workerThread start];

I know there is no "join" function in NSThread, what is the best way to stop this thread & wait for 2 seconds for the thread to die? (like in Java Thread join(2000) function)

[workerThread cancel]
//how to wait for 2 seconds for the thread to die? I need something like join(2000) in Java

(Please don't talk GCD, my question is about NSThread, thanks.)

Leem.fin
  • 40,781
  • 83
  • 202
  • 354
  • 1
    What about this question: http://stackoverflow.com/questions/7952653/sleep-or-pause-nsthread ? – flashspys Aug 10 '16 at 14:09
  • @flashspys , apparently the link has nothing to do with my question. It talks about make the thread sleep, my question is about wait for thread to be killed. If you check the documentation of Java join() function I linked in my question, you will understand what I need. – Leem.fin Aug 10 '16 at 14:19
  • I read "to die" over, I'm sorry. I think without the use of gcd or NSOperationQueue its not possible. The API of NSThread is not very extensive. – flashspys Aug 10 '16 at 14:24

1 Answers1

0

Stoping the caller thread is not a good idea imho, if possible, not sure apple like that, but you can get a workaround...

I see to way of doing so :

1/ quick and dirty NSTimer that would check every x second the thread state, not my cup of tea though.

2/ in your doWork selector post a NSNotification when the job is done, and register for it, and when it's fired, you know your thread is done...

I do love the 2nd solution better, and yes, GCD rox so here is how I'd do that:

static NSThread * workerThread;

- (void) startWorkerThread
{
    workerThread = [[NSThread alloc] initWithTarget:self selector:@selector(doWork)  object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(workerThreadDidReturn) name:@"workerThreadReturnsNotification" object:nil];
    [workerThread start];

    static NSInteger timeoutSeconds = 5;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(timeoutSeconds * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // Cancel after timeoutSeconds seconds if not finished yet
        if(![workerThread isCancelled]){
            [workerThread cancel];
        }
    });

}

- (void) doWork
{

    // Do something heavy...
    id result = [NSObject new];

    [[NSNotificationCenter defaultCenter] postNotificationName:@"workerThreadReturnsNotification"
                                                        object:result];
}


- (void) workerThreadDidReturn:(NSNotification *)notif
{
    id result = (id) notify.object;
    // do something with result...

    [workerThread cancel];
}
Florian Burel
  • 3,408
  • 1
  • 19
  • 20