Grand Central Dispatch - Examples

Examples

Two examples that demonstrate the use of Grand Central Dispatch can be found in John Siracusa's Ars Technica Snow Leopard review. Initially, a document-based application has a method called analyzeDocument which may do something like count the number of words and paragraphs in the document. Normally, this would be a quick process, and may be executed in the main thread without the user noticing a delay between pressing a button and the results showing.

- (IBAction)analyzeDocument:(NSButton *)sender { NSDictionary *stats = ; ; ; ; }

If the document is large and analysis takes a long time to execute then the main thread will stall waiting for the function to finish. If it takes long enough, the user will notice, and the application may even "beachball". The solution can be seen here:

- (IBAction)analyzeDocument:(NSButton *)sender { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ NSDictionary *stats = ; dispatch_async(dispatch_get_main_queue, ^{ ; ; ; }); }); }

Here, the call to is placed inside a Block, which is then placed on one of the global concurrent queues. After it has finished running , a new block is placed on the main queue (on which the main thread of the application runs), which updates the GUI (This is necessary because the GUI can only be updated by the main thread). By making these two small changes, the developer has avoided a potential stall of the application as seen by the user, and allowed their application to make better use of hardware resources.

The second example is that of parallelising a for loop:

for (i = 0; i < count; i++) { results = do_work(data, i); } total = summarize(results, count);

This code runs the do_work function count times, assigning the ith result to the ith element in the array results, and then calls summarize on array once the loop has ended. Unfortunately the work is computed sequentially, where it may not need to be. Assuming that do_work doesn't rely on the results of any of the other calls made to it, there is no reason why these calls cannot be made concurrently. This is how this would be done in GCD:

dispatch_apply(count, dispatch_get_global_queue(0, 0), ^(size_t i){ results = do_work(data, i); }); total = summarize(results, count);

Here, dispatch_apply runs the block passed to it, count times, placing each invocation on a global queue, and passing each block invocation a different number from 0 to count-1. This will allow the OS to spread out the work as it sees fit, choosing the optimal number of threads to run on for the current hardware and system load. dispatch_apply does not return until all the blocks it places on the given queue have completed execution, so that it can be guaranteed that all the work inside the original loop has completed before calling summarize.

Programmers can create their own serial queues for tasks which they know must run serially but which may be executed on a separate thread. A new queue would be created like so:

dispatch_queue_t exampleQueue; exampleQueue = dispatch_queue_create( "com.example.unique.identifier", NULL ); // exampleQueue may be used here. dispatch_release( exampleQueue );

Care must be taken to avoid a dispatched block on a queue synchronously placing another block on the same queue as this is guaranteed to deadlock. Such code might do the following:

dispatch_queue_t exampleQueue = dispatch_queue_create( "com.example.unique.identifier", NULL ); dispatch_sync( exampleQueue, ^{ dispatch_sync( exampleQueue, ^{ printf( "I am now deadlocked...\n" ); }); }); dispatch_release( exampleQueue );

Read more about this topic:  Grand Central Dispatch

Famous quotes containing the word examples:

    No rules exist, and examples are simply life-savers answering the appeals of rules making vain attempts to exist.
    André Breton (1896–1966)

    There are many examples of women that have excelled in learning, and even in war, but this is no reason we should bring ‘em all up to Latin and Greek or else military discipline, instead of needle-work and housewifry.
    Bernard Mandeville (1670–1733)

    Histories are more full of examples of the fidelity of dogs than of friends.
    Alexander Pope (1688–1744)