How to stop a NSThread sub-thread in iphone

15,663

Solution 1

The cancel method only informs the thread that it is cancelled (as you mentioned changes the isCancelled to YES. It's then the responsibility of the thread itself to check this and exit. For example, in your MyThread: method you could do this:

// At some checkpoint
if([[NSThread currentThread] isCancelled]) {
    /* do some clean up here */
    [NSThread exit];
}

You should do this check periodically, and exit from within the thread as shown; otherwise the cancel doesn't have any effect.

Solution 2

-(void)cancel

Discussion The semantics of this method are the same as those used for the NSOperation object. This method sets state information in the receiver that is then reflected by the isCancelled method. Threads that support cancellation should periodically call the isCancelled method to determine if the thread has in fact been cancelled, and exit if it has been.

more information see NSThread API Reference

Share:
15,663
None
Author by

None

Updated on July 24, 2022

Comments

  • None
    None almost 2 years

    I created a sub-thread using NSThread in main thread

    NSThread *newThread = [[NSThread alloc] initWithTarget:self selector:@selector(MyThread:) object:timer];

    5 sec later,i used [newThread cancel] in main thread to stop the sub-thread,but it didnt work,

    Method MyThread: in newThread still working

    so,whats the correct answer to stop newThread,THX

    actually [newThread isCancelled] is YES,but selector MyThread was still woking

  • None
    None almost 14 years
    you mean a thread can only be cancelled by itself,not by another thread or main thread?
  • Chuck
    Chuck almost 14 years
    @None: It means that "cancelling" a thread doesn't do what you think. When you cancel a thread, it causes isCancelled to return YES. The thread should then stop executing. It doesn't force the thread to immediately stop execution, though — that would be troublesome if it had any resources open.
  • None
    None almost 14 years
    @Chuck:Thank you, but if I want stop a sub-thread in main thread,how should I do?
  • bbum
    bbum almost 14 years
    Effectively, you can't. There is no way to know what state the thread is in when killed and, thus, no way -- beyond the isCancelled mechanism -- to safely kill a thread from another thread.