I am building an iOS app which does some heavy lifting on a background thread.
I create my thread using
dispatch_queue_t backgroundQueue;
backgroundQueue = dispatch_queue_create("MyQueue", NULL);
and then put it into GCD using:
dispatch_async(backgroundQueue, ^
{
//some heavy operations here
//each of them might run for >1 sec
}
I just want a sequential execution of the queue, provided it doesn't block the main thread. If this block is called from method 3, method 2 and method 1 within 20ms.... they should be necessarily executed in the order 3 -> 2 -> 1, since the output of each method is used up by the next.
I am new to GCD and naively imagined a dispatch queue would use a FIFO queue to execute sequential calls. However, in its current implementation, it is far from sequential.
I tried using NSLock, but they didn't help either.
I would like to know the proper mechanism for enforcing sequential execution in GCD.
EDIT 1:
I am declaring a global queue:
dispatch_queue_t backgroundQueue ;
and initiating it in viewDidLoad() :
backgroundQueue = dispatch_queue_create("MyQueue", DISPATCH_QUEUE_SERIAL);
//using DISPATCH_QUEUE_SERIAL was a new idea, I also tried using NULL
I'm using GCD to basically call method in another class:
-(void)doAction()
{
dispatch_async(backgroundQueue, ^
{
MyOtherClass *obj = [[MyOtherClass alloc] init];
[obj heavyMethod1: param1 : param2];
[obj release];
});
}
-(void)doAnotherAction()
{
dispatch_async(backgroundQueue, ^
{
MyOtherClass *obj = [[MyOtherClass alloc] init];
[obj heavyMethod2: param3 : param4];
[obj release];
});
}
Now, doAction and doAnotherAction method are being called from a number of other methods, depending upon the scenario.
What I'm seeing here is - if I'm calling these methods in the sequence :: doAction -> doAction -> doAnotherAction -> doAction
...I'm getting an output in a sequence like :: doAction -> doAnotherAction -> doAction -> doAction
How do I maintain its sequence of invokation and keep it serial at the same time ?
P.S: - If I remove GCD and allow things to carry on in the main thread, it is theoretically running fine - in simulator. (It crashes in iPhone.)