objective-ciosmacoscocoagrand-central-dispatch

Using Grand Central Dispatch outside of an application or runloop


In the GCD documentation it's quite clear that to submit work to the main queue, you need to either be working within an NSApplication (or UIApplication) or call dispatch_main() to act as a run loop of sorts. However, do I need to do anything to set up the global concurrent queue?

Basically what I am asking is: If I write a plain simple C program, do I need to perform any special setup before I go dispatch_get_global_queue() and start giving it work?


Solution

  • No, you don't need any additional setup. But you need to call dispatch_main() to start the GCD dispatcher.
    As dispatch_main() never returns, this will also prevent your main function from reaching it's return.

    Example for a minimal C program that uses GCD & a global queue (based on http://wiki.freebsd.org/GCD):

    #include <dispatch/dispatch.h>
    #include <err.h>
    #include <stdio.h>
    #include <stdlib.h>
    
    int main(int argc, char *argv[])
    {
        dispatch_queue_t globalQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        dispatch_time_t dispatchTime = dispatch_time(DISPATCH_TIME_NOW, 5LL * NSEC_PER_SEC);
        dispatch_after(dispatchTime, globalQueue, ^{
            printf("Dispatched on global queue\n");
            exit(0);
        });
        dispatch_main();
        return (0);
    }
    

    To compile this, use:

    clang -Wall -Werror -fblocks -L/usr/local/lib -I/usr/local/include -o test test.c