Objective-c – FIFO serial queue using GCD

fifogrand-central-dispatchobjective cobjective-c-blocks

I am trying to create a (network) synchronized array for the company I work for. While the networking part works fine, I have dwelled into an issue.

My wish was to create a new queue using dispatch_create_queue, to which I would add two blocks that are not to run on the main thread, but in a serial manner, meaning that first the first block has to run, then the second, and never in parallel.

I've read the apple documentation, but it is confusing to say the least.

  • When I create my queue using dispatch_queue_create and then add the blocks (after they have been defined) using dispatch_sync, I have found out that the block is still executing on the main thread.

  • When using dispatch_async, thats when the blocks are not executing on the main thread.

  • When I try to add both blocks using dispatch_sync They get blocked forever.

  • The only time that both blocks seem to run fine and off the main thread is when calling dispatch_async.

However the reason why I chose GCD and the sync method so that I was under the impression that I was creating a new queue (and thus a new thread) and that adding blocks to that queue would simply block one until the other had finished executing. Is this not the case, or does creating a queue does not guarantee that the code will not run on the main thread ?

Best Answer

This is a FIFO queue in GCD:

dispatch_queue_t serialQueue = dispatch_queue_create("com.blah.queue", DISPATCH_QUEUE_SERIAL);

...
dispatch_async(serialQueue, ^{
    //block1
});

dispatch_async(serialQueue, ^{
    //block2
});