Note that there are some explanatory texts on larger screens.

plurals
  1. POiOS multithreading synchronization
    text
    copied!<p>I am building an iOS app which does some heavy lifting on a background thread.</p> <p>I create my thread using</p> <pre><code> dispatch_queue_t backgroundQueue; backgroundQueue = dispatch_queue_create("MyQueue", NULL); </code></pre> <p>and then put it into GCD using:</p> <pre><code> dispatch_async(backgroundQueue, ^ { //some heavy operations here //each of them might run for &gt;1 sec } </code></pre> <p>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.</p> <p>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.</p> <p>I tried using NSLock, but they didn't help either.</p> <p>I would like to know the proper mechanism for enforcing sequential execution in GCD.</p> <p><strong>EDIT 1:</strong></p> <p>I am declaring a global queue:</p> <pre><code> dispatch_queue_t backgroundQueue ; </code></pre> <p>and initiating it in viewDidLoad() : </p> <pre><code> backgroundQueue = dispatch_queue_create("MyQueue", DISPATCH_QUEUE_SERIAL); //using DISPATCH_QUEUE_SERIAL was a new idea, I also tried using NULL </code></pre> <p>I'm using GCD to basically call method in another class:</p> <pre><code> -(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]; }); } </code></pre> <p>Now, doAction and doAnotherAction method are being called from a number of other methods, depending upon the scenario. </p> <p>What I'm seeing here is - if I'm calling these methods in the sequence :: doAction -> doAction -> doAnotherAction -> doAction</p> <p>...I'm getting an output in a sequence like :: doAction -> doAnotherAction -> doAction -> doAction</p> <p>How do I maintain its sequence of invokation and keep it serial at the same time ?</p> <p>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.)</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload