Note that there are some explanatory texts on larger screens.

plurals
  1. POwhen is it safe to release an NSThread?
    text
    copied!<p>Below is the runloop for my secondary NSThread* processThread</p> <p>To close the thread I call</p> <pre><code>//cancel secondary thread [processThread cancel] //signal condition [processCondition broadcast]; </code></pre> <p><strong>Is it then safe to then call:</strong></p> <pre><code>[processCondition release]; [processThread release]; </code></pre> <p><strong>or do i need to be sure that the thread has finished?</strong> <br> <br> Perhaps like this?</p> <pre><code>NSTimeInterval timeout = [NSDate timeIntervalSinceReferenceDate] + (1.0/15.0); while ([processThread isExecuting] &amp;&amp; [NSDate timeIntervalSinceReferenceDate] &lt; timeout) { [NSThread sleepForTimeInterval: 1.0/1000.0 ]; } [processCondition release]; [processThread release]; </code></pre> <p><br> <br> <br> <i>detailed code and explanation:</p> <pre><code>- (void)processLoop { NSAutoreleasePool * outerPool = [[NSAutoreleasePool alloc] init]; [processCondition lock]; //outer loop //this loop runs until my application exits while (![[NSThread currentThread] isCancelled]) { NSAutoreleasePool *middlePool = [[NSAutoreleasePool alloc]; if(processGo) { //inner loop //this loop runs typically for a few seconds while (processGo &amp;&amp; ![[NSThread currentThread] isCancelled]) { NSAutoreleasePool *innerPool = [[NSAutoreleasePool alloc]; init]; //within inner loop //this takes a fraction of a second [self doSomething]; [innerPool release]; } [self tidyThingsUp]; } else { [processCondition wait]; } [middlePool release]; } [processCondition unlock]; [outerPool release]; } </code></pre> <p>the combination of:</p> <ul> <li>an inner while loop</li> <li>NSCondition *processCondition</li> <li>toggling <code>processGo</code> between <code>YES</code> and <code>NO</code></li> </ul> <p>allows me to stop and start the inner while loop without cancelling the thread. </p> <pre><code>if (processGo == YES) </code></pre> <p><br> execution enters the inner while loop.<br></p> <p>When the main thread sets</p> <pre><code>processGo = NO </code></pre> <p>execution leaves the inner while loop and tidys up <br> on the next pass of the outer loop, execution hits</p> <pre><code>[processCondition wait] </code></pre> <p>and waits</p> <p>if the the main thread resets</p> <pre><code>processGo == YES </code></pre> <p>and calls</p> <pre><code>[processCondition wait] </code></pre> <p>execution re-enters the inner loop </i></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload