End a while loop that is running in a secondary thread?

Discussion in 'Mac Programming' started by shakeman0, Aug 19, 2011.

  1. shakeman0 macrumors 6502a


    Jul 20, 2009
    I have an application where the user inputs how many times the application should repeat an action. The user inputed value is taken and used in a while loop that repeats the action the user specified amount of times. The process can be very long and I would like to have a button that would allow the user to end the process. I have moved the repeat process to a secondary thread (NSThread) so that the user can continue to interact with the user interface while the process is running. I'm having trouble stopping the repeat process when the user presses the "Stop" button. What is the best way to allow my main thread to communicate to a secondary thread that it needs to stop a while loop running in it? Any help would be greatly appreciated.



    This didn't seem to work for me... I declared two atomic NSNumbers using @property (atomic, retain). They are both set to have an integer value of 0. Here is my loop that runs in the method run in the secondary thread:

     int i = 0;
     while (i < timesToRun && [numberOne intValue] == 0) { 
     [self doSomething]; 
     numberOne = numberTwo;
    My stop button calls a method that changes the integer value of numberTwo to "1". For some reason this isn't stopping the loop. Am I doing something incorrectly?
  2. jiminaus macrumors 65816


    Dec 16, 2010
    You're reinventing the wheel, badly. If you're using NSThread or NSOperation, you send cancel and the loop sends isCancelled to check if it should stop.
  3. shakeman0 thread starter macrumors 6502a


    Jul 20, 2009
    Thank you for the reply. I wasn't aware of isCancelled. Unfortunately, it doesn't seem to be canceling the thread either...
  4. gnasher729 macrumors P6


    Nov 25, 2005
    Typical explanation would be that you send the message to the wrong object. Put some NSLog statements in the right places, where the thread is supposed to be cancelled, and where you check for it being cancelled.

Share This Page