Stocptimal
Stocptimal

Reputation: 93

Why will the following simple grand central dispatch program not work correctly?

So I was expecting the following program to print two lines. However it doesn't print anything. Any ideas on what needs to be fixed?

#import <Foundation/Foundation.h>
#import <dispatch/dispatch.h>

int main(int argc, char **argv)
{
 dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), ^{
 printf("Done outer async\n");
    dispatch_async(dispatch_get_main_queue(),^{
         printf("Done inner sync");
    });
 });

 return 0;
}

Thanks

Upvotes: 3

Views: 543

Answers (2)

Martin R
Martin R

Reputation: 539705

You have to call dispatch_main() if your program does not have an event loop:

int main(int argc, char **argv)
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), ^{
        printf("Done outer async\n");
        dispatch_async(dispatch_get_main_queue(),^{
            printf("Done inner sync");
        });
    });

    dispatch_main();
    return 0;
}

From the documentation:

This function "parks" the main thread and waits for blocks to be submitted to the main queue. Applications that call UIApplicationMain (iOS), NSApplicationMain (Mac OS X), or CFRunLoopRun on the main thread must not call dispatch_main.

Upvotes: 6

Nick C
Nick C

Reputation: 514

Your main thread ends first, shutting down the rest when you return 0 -- this is why nothing is printed since your other dispatches don't get a chance to be executed.

Upvotes: 2

Related Questions