Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple GCD Serial Queue example like FIFO using blocks

I read Apple documentation on how to Use serial queues to ensure that tasks to execute in a predictable order but now i am confused too much.
Some how i am able to work serially but still i am not clear so i need simple serial example for my methods to execute serially.

I divided my functionality in to 4 parts and now want them to execute Serially

[self ReadAllImagesFromPhotosLibrary];

[self WriteFewImagestoDirectory];

[self GettingBackAllImagesFromFolder]; 

[self MoveToNextView];
like image 847
DreamWatcher Avatar asked Jul 02 '13 09:07

DreamWatcher


2 Answers

To follow-up and improve iCoder's answer, you could and should do the following.

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

dispatch_async(serialQueue, ^{
        [self ReadAllImagesFromPhotosLibrary];
    }); 
dispatch_async(serialQueue, ^{
         [self WriteFewImagestoDirectory];
});
dispatch_async(serialQueue, ^{
    [self GettingBackAllImagesFromFolder]; 
});
dispatch_async(serialQueue, ^{
    [self MoveToNextView];
});

Despite the above calls being async, they will be queued and run serially as the DISPATCH_QUEUE_SERIAL states. The difference between sync and async is that with sync, your code will pause and wait for the block answer before running the following code, thus potentially freezing your UI if the execution time is long. Whereas with async, the code runs on and the block is returned asynchronously.

However, the tasks you have stored in the DISPATCH_QUEUE_SERIAL will wait and be executed one after the other in the order they were added, thanks to GCD (Grand Central Dispatch).

like image 131
Benjamin Avatar answered Oct 15 '22 06:10

Benjamin


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

dispatch_async(serialQueue, ^{
        [self ReadAllImagesFromPhotosLibrary];
             dispatch_async(serialQueue, ^{
                     [self WriteFewImagestoDirectory];
                     dispatch_async(serialQueue, ^{
                         [self GettingBackAllImagesFromFolder]; 
                         dispatch_async(serialQueue, ^{
                              [self MoveToNextView];
                         });
                   });
              });
    }); 

I think the above code should work, but make sure the UI operations are executed in the main thread. Hope it helps.

like image 39
iCoder Avatar answered Oct 15 '22 07:10

iCoder