title: Implementing Critical section using GCD in iOS
body: <p>I have a really heavy task to perform, and I dont want to block the main thread. So I'm starting a <strong>separate Concurrent queue</strong> for it. There can be 4 instances of the said task.</p>
  
  <pre><code>-(dispatch_queue_t)getConcurrentQueue
  {
      if(concurrentQueue == nil)
      {
          concurrentQueue = dispatch_queue_create("com.myself.HeavyTask", DISPATCH_QUEUE_CONCURRENT);
      }
      return concurrentQueue;
  }
  </code></pre>
  
  <p>Now to start the heavy task I have - </p>
  
  <pre><code>-(void)beginTask
  {
        //.....
        //.....
          __weak typeof(self) weakSelf = self;
          dispatch_queue_t queue = [self getConcurrentQueue];
          dispatch_async(queue, ^{
              [weakSelf heavyTask];
          });
  }
  </code></pre>
  
  <p>Now the method heavyTask goes like this -- </p>
  
  <pre><code>-(void)heavyTask
  {
       //...
       dispatch_sync(dispatch_get_current_queue(), ^{
       // Initialising code for heavy task
       // This is the critical section. Only one of the 4 concurrent threads can enter this at a time
       }
       //....
  
       while(condition)
       {
          // Perform meat of the task
       }
  
       //...
       dispatch_sync(dispatch_get_current_queue(), ^{
       // Teardown code. Freeing memory etc.
       // This is also a critical section.
       }
       //...
  }
  </code></pre>
  
  <p>The initialising code and teardown code uses some 3rd party C methods which are not thread safe. So making them thread safe is not the scope of the question.</p>
  
  <p>Now I've put the <code>"initialising code"</code> and and the <code>"teardown code"</code> within - </p>
  
  <pre><code>dispatch_sync(dispatch_get_current_queue(), ^{
  }
  </code></pre>
  
  <p>My code is crashing and I'm getting error messages stating that there is insufficient thread locking around the critical section code.</p>
  
  <p>I read that <code>dispatch_get_current_queue()</code> is not safe, so I replaced it with <code>concurrentQueue</code>. I also tried replacing with <code>dispatch_get_main_queue()</code>. Still the code crashes, complaining about insufficient thread locking.</p>
  
  <p><strong>I know there is something wrong in my understanding of implementing critical section using GCD.</strong></p>
  
  <p><strong>Can anyone clearly show me how to make my code work properly here??</strong> </p>
  
  <p>Side question -- <strong>Can I use <code>@synchronized { }</code> blocks here??</strong></p>