Search code examples
objective-cmacosasynchronousosx-mavericksdispatch-async

Convert FIFO dispatch_async queue to concurrent


This code, while working, executes the two tasks in FIFO order:

-(void) update {

    @autoreleasepool {

        dispatch_queue_t queue = dispatch_queue_create("us.yellosoft", 0);

        // inpternal address
        dispatch_async(queue,^(){

            // TODO: implement NSProgressIndicator logic

            [internalIpMenuItem setTitle: @"Updating..."];

            // get IP address from [[NSHost currentHost] addresses]...
            NSString *localIP = [self getLocalIP];

            // change UI
            [internalIpMenuItem setTitle: localIP];

        });

        // external address
        dispatch_async(queue, ^(){

            // TODO: implement NSProgressIndicator logic

            [externalIpMenuItem setTitle: @"Updating..."];

            // get IP address from external JSON service...
            NSString *externalIP = [AddressService getIPaddress];

            // change UI
            [externalIpMenuItem setTitle: localIP];

        });

    }

}

I would like to have two tasks run concurrently. Is this possible?


Solution

  • You "can", but you need to dispatch to the main thread if you use UIKit methods anyway.

    In order to parallelize work, you should use the global concurrent queue. Using your own concurrent dispatch queue, realy only makes sense if you want to synchronize access to shared resources - in which case you would need to use dispatch_barrier_async and dispatch_barrier_sync.