0

I would like to explain what I want to do by using C language with pthreads

pthread_t tid1, tid2;

void *threadOne() {
    //some stuff
}

void *threadTwo() {
    //some stuff
    pthread_cancel(tid1);
    //clean up          
}

void setThread() {
    pthread_attr_t attr;
    pthread_attr_init(&attr);
    pthread_create(&tid1,&attr,threadOne, NULL);
    pthread_create(&tid2,&attr,threadTwo, NULL);
    pthread_join(tid2, NULL);
    pthread_join(tid1, NULL);
}

int main() {
    setThread();
    return 0;
}

So the above is what I want to do in objective-c. This is what I use in objective-c to create threads:

[NSThread detachNewThreadSelector:@selector(threadOne) toTarget:self withObject:nil];

As I do not declare and initialise anything like thread id, I do not know how to cancel one thread from another thread. Can someone convert my C code into objective-c or recommend me something else?

Sarp Kaya
  • 3,686
  • 21
  • 64
  • 103

2 Answers2

0

Try this.

   -(void)threadOne
    {
        [[NSThread currentThread] cancel];
    }
Lee
  • 1
  • 1
  • Why should I cancel the current thread? If you look at the code snippet that I've provided I cancel the threadOne from threadTwo... It's definitely a wrong answer! – Sarp Kaya Dec 20 '12 at 04:10
0

The class method detachNewThreadSelector:toTarget:withObject: doesn't return an NSThread object, but it's just a convenience method.

[NSThread detachNewThreadSelector:@selector(threadOne) toTarget:self withObject:nil];

is pretty much the same as:

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

Except that the latter method gives you a pointer to the created NSThread object, on which you can then use methods like cancel.

Note that like pthreads, NSThread cancellation is advisory; it's up to your code running in that thread to check the thread's isCancelled state and respond appropriately. (You can get a reference to the currently running NSThread with the class method currentThread.)

rickster
  • 124,678
  • 26
  • 272
  • 326