Note that there are some explanatory texts on larger screens.

plurals
  1. PODispatch queues: How to tell if they're running and how to stop them
    primarykey
    data
    text
    <p>I'm just playing around with GCD and I've written a toy CoinFlipper app.</p> <p>Here's the method that flips the coins:</p> <pre><code>- (void)flipCoins:(NSUInteger)nFlips{ // Create the queues for work dispatch_queue_t mainQueue = dispatch_get_main_queue(); dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, NULL); // Split the number of flips into whole chunks of kChunkSize and the remainder. NSUInteger numberOfWholeChunks = nFlips / kChunkSize; NSUInteger numberOfRemainingFlips = nFlips - numberOfWholeChunks * kChunkSize; if (numberOfWholeChunks &gt; 0) { for (NSUInteger index = 0; index &lt; numberOfWholeChunks; index++) { dispatch_async(queue, ^{ NSUInteger h = 0; NSUInteger t = 0; flipTheCoins(kChunkSize, &amp;h, &amp;t); dispatch_async(mainQueue, ^{ self.nHeads += h; self.nTails += t; }); }); } } if (numberOfRemainingFlips &gt; 0) { dispatch_async(queue, ^{ NSUInteger h = 0; NSUInteger t = 0; flipTheCoins(numberOfRemainingFlips, &amp;h, &amp;t); dispatch_async(mainQueue, ^{ self.nHeads += h; self.nTails += t; }); }); } } </code></pre> <p>As you can see; I'm breaking the number of flips into large chunks flipping them in the background and updating properties in the main queue. The properties are being observed by the window controller and an UI is updated with the running results.</p> <p>I've looked through the Concurrency Programming Guide and the GCD docs, and although there is a way to suspend a queue, there isn't a way to stop them, and remove all queued and not running objects.</p> <p>I'd like to be able to hook up a 'stop' button to cancel flipping once it's started. With <code>NSOperationQueue</code> I can observe the <code>operationCount</code> property to know if it's running, and <code>cancelAllOperations</code> to remove queued blocks.</p> <p>I've looked through the Concurrency Programming Guide and the GCD docs, and although there is a way to suspend a queue, there isn't a way to stop them, and remove all queued and not running objects.</p> <p>So :- </p> <ol> <li>How do I tell if blocks I've added to a queue are still waiting?</li> <li>How do I cancel blocks that haven't run yet?</li> <li>I'm new to the GCD stuff, so am I doing it right?</li> </ol>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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