views:

667

answers:

2

I start a background thread 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?

+1  A: 

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.

darren
One doubt, So if I use NSLock will the background thread be able to see the values of a global variable that i set/change from the main thread OR can it see otherwise also?
wolverine
threads share the same address space, so global variables are truly global to all threads. Of course you must lock on them to avoid race conditions, and that is where NSLock comes in.
darren
If you're using a scalar value, like a BOOL, you should be safe without the use of an NSLock.
Brad Larson
What do you mean by scalar value? as opposed to vector value? I don't think an int (scalar) would be safe to use without a lock.
darren
I mean that as a single-valued primitive type. If you have two or more threads that manipulate a single value, then yes, you will need to lock around it to prevent problems. However, if you manipulate it in one thread, and read from it in another, you should be safe without a lock. NSLock and friends can be pretty expensive.
Brad Larson
A: 

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.

Ralf Edmund