3
votes

In my iOS app I'm running a computationally intensive task on a background thread like this:

// f is called on the main thread
- (void) f {
    [self performSelectorInBackground:@selector(doCalcs) withObject:nil]; 
}

- (void) doCalcs {
    int r = expensiveFunction();
    [self performSelectorOnMainThread:@selector(displayResults:) withObject:@(r) waitUntilDone:NO];
}

How can I use GCD to run an expensive calculation such that it doesn't block the main thread?

I've looked at dispatch_async and some options for the GCD queue choice but I'm too new to GCD to feel like I understand it sufficiently.

1
What did you try after looking at dispatch_async ?Wain
@Wain just reading about the various queue choices and trying to understand when GCD would run something on a background thread or perhaps asynchronously on the main thread.SundayMonday
so you found the way to get the main queue, the global queue (for a priority) and a specifically created queue ?Wain

1 Answers

10
votes

You use dispatch_async like suggested.

For example:

    // Create a Grand Central Dispatch (GCD) queue to process data in a background thread.
dispatch_queue_t myprocess_queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0);

// Start the thread 

dispatch_async(myprocess_queue, ^{
    // place your calculation code here that you want run in the background thread.

    // all the UI work is done in the main thread, so if you need to update the UI, you will need to create another dispatch_async, this time on the main queue.
    dispatch_async(dispatch_get_main_queue(), ^{

    // Any UI update code goes here like progress bars

    });  // end of main queue code block
}); // end of your big process.
// finally close the dispatch queue
dispatch_release(myprocess_queue);

That's the general gist of it, hope that helps.