grand central dispatch

I was given this code but I don't see the results of the NSLog statement in the debug log window:


dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

dispatch_async(queue, ^{

NSLog(@"Block for asynchronous execution");

});


I find this code in the very last section of this page:


https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/WorkingwithBlocks/WorkingwithBlocks.html

In what context are you running the above code? In particular, is this in an app? Or is it in a command-line tool? If it's in a command-line tool, it's common to unthinkingly allow the program to exit (by returning from main()) and thus prevent background threads from completing their work.

I run that code in main() of a command line tool project for OS X.


What should I do to be able to see the code work?

You will need to block the main thread of the command line tool until the async work you’re started via

dispatch_async
is complete. The best approach depends on your specific situation. For example:
  • You could just a dispatch group (

    dispatch_group_create
    ), enter the group when you start work (
    dispatch_group_enter
    ), leave the group when the work is done (
    dispatch_group_leave
    ), and have the main thread wait for the group to be done (
    dispatch_group_wait
    ).
  • You could ‘park’ the main thread in

    dispatch_main
    and then have the work, when it’s done, explicitly exit the tool by calling
    exit
    .
  • You could combine these techniques by using a notifying dispatch group (

    dispatch_group_notify
    ).

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"

WWDC runs Mon, 13 Jun through to Fri, 17 Jun. During that time all of DTS will be at the conference, helping folks out face-to-face. http://developer.apple.com/wwdc/

grand central dispatch
 
 
Q