views:

279

answers:

2

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

+2  A: 

cancal 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.

Mo
you mean a thread can only be cancelled by itself,not by another thread or main thread?
None
@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.
Chuck
@Chuck:Thank you,but if I want stop a sub-thread in main thread,how should I do?
None
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.
bbum
A: 

-(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

py_zhu