How to stop a NSThread sub-thread in iphone
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
None
Updated on July 24, 2022Comments
-
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 almost 14 yearsyou mean a thread can only be cancelled by itself,not by another thread or main thread?
-
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 returnYES
. 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 almost 14 years@Chuck:Thank you, but if I want stop a sub-thread in main thread,how should I do?
-
bbum almost 14 yearsEffectively, 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.