1

My app has to do a lot of syncing between the cloud database and core data, and this occurs in various methods. I do this using simple background threads:

dispatch_queue_t backgroundThread = dispatch_queue_create("background thread", NULL);

dispatch_async(backgroundThread, ^{ ...

However, if I do stuff too rapidly in the app, different synchronization tasks can occur simultaneously, which can cause unintended results.

Thus, I want to perform all synchronization tasks serially on just one thread. Whenever I need to perform a synchronization task, I want to dispatch it to the dedicated thread, not to be executed until that thread completes all previously submitted tasks. How should I manage that? Specifically...

  1. How should I instantiate my background serial thread?
  2. Should I take steps to retain it for the life of the app, or--not sure whether this is an issue--let it be released when not in use and then recreate it?
  3. How do I refer to it/dispatch to it from various methods/objects?

I've not been able to find an answer directly addressing this situation. This one (Using a single shared background thread for iOS data processing?) came close, but shied away.

Thanks for your time.

Community
  • 1
  • 1
mkc842
  • 2,361
  • 2
  • 26
  • 38

1 Answers1

3

Access the queue through a static function like this:

static dispatch_queue_t my_serial_queue() {

    static dispatch_queue_t s_serial_queue;
    static dispatch_once_t s_done;
    dispatch_once(&s_done, ^{s_serial_queue = dispatch_queue_create("com.app.my_queue_name", DISPATCH_QUEUE_SERIAL);});
    return s_serial_queue;
}

Then use it like this...

dispatch_sync(my_serial_queue(), ^{
    //do something here
});
combinatorial
  • 9,132
  • 4
  • 40
  • 58
  • Actually, I get an error saying that a semicolon is expected after that () on the first line. – mkc842 Feb 24 '14 at 17:31
  • Do you mean in the declaration of my_serial_queue()? Can you give the full error message? – combinatorial Feb 24 '14 at 21:30
  • Ahh a "static function" can't be declared inside a method. I'm familiar with blocks but not functions. Anyway, got it, thanks. – mkc842 Feb 25 '14 at 22:27
  • Sorry to drag this out, but I found that this runs my code on the main thread unless I use dispatch_async. Why might that be? – mkc842 Mar 26 '14 at 18:08
  • see http://stackoverflow.com/questions/13972048/dispatch-sync-always-scheduling-a-block-on-main-thread specifically Apple says "As an optimization, this function invokes the block on the current thread when possible." – combinatorial Mar 26 '14 at 22:21
  • 1
    it's worth remembering that a queue is not the same as a thread – combinatorial Mar 26 '14 at 22:21