How to stop a NSThread sub-thread in iphone
Asked Answered
P

2

9

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

Parodist answered 7/7, 2010 at 1:41 Comment(0)
D
11

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.

Duckbill answered 7/7, 2010 at 2:14 Comment(4)
you mean a thread can only be cancelled by itself,not by another thread or main thread?Parodist
@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.Unhopedfor
@Chuck:Thank you, but if I want stop a sub-thread in main thread,how should I do?Parodist
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.Gunpaper
M
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

Maun answered 5/10, 2010 at 13:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.