Synchronization UI code with GCD

I came across a situation where multiple threads were attempting to display a loading view. This was sometimes causing race conditions.

Enter synchronization. This article does a great job of explaining various techniques for performing synchronization.

Because I was working with with UI components, this is the pattern I eventually settled on. If you have a different or better way to do it, let me know!

Step 1: Create a dispatch_queue_t data member

dispatch_queue_t _lock;  
_lock = dispatch_queue_create("", nil);  

Step 2: Use the dispatch queue to serialize calls to the code:

// dispatch on lock queue to serialize request
dispatch_async(_lock, ^{

  // dispatch sync on main queue to perform UI activity
  dispatch_sync(dispatch_get_main_queue(), ^{
    // do some stuff with UI

comments powered by Disqus