How can i stop the background thread from the main thread in Iphone NSthread?
I start a background thread 开发者_StackOverflow社区from my program while my main thread is checking something. If the checking goes false, I want to stop the running background thread and start it all over again with my new parameters.
I want to stop it coz the thread will be downloading images and if I doesnt stop it and call it again, it will take a lot of time for the new images to get downloaded. Is it possible to do so?
In my experience, its usually best to let a thread exit gracefully by itself. How about having some common variable that the main thread could set to false if things go awry. The second thread could periodically check this variable and if it has been set to false, it knows it should clean up and return.
I think you could use condition variables in a more elegant fashion, but his approach with the proper use of NSLock should work.
NSThread implements a method -(void)cancel
that sets state information in the receiving thread to indicate, it should exit. The receiving background thread should - if behaving properly - regulary check whether it is cancelled using -(BOOL)isCancelled
.
This way the receiver has a chance to clean up it's acquired resources in a proper way.
Looking into the Java language thread semantic, this apparatus works quite the same way. Javas Thread implements two methods void Thread.interrupt()
and boolean Thread.isInterrupted()
.
In case long running background operations do not react to an attempt to -cancel
them, i would see this as an serious problem and file a bug report / change request.
You may wait on the termination of the background thread by regulary calling either -(BOOL)isFinished
or -(BOOL)isExecuting
on the background NSThread
. Unfortunately the NSDidBecomeSingleThreadedNotification
is not supported on the iPhone plattform.
精彩评论