4

When I submit two blocks into a serial queue by dispatch_async, does it assure the second one runs after the first one:

  • dispatch_async(serial_queue, b1);
  • dispatch_async(serial_queue, b2);

can we assure b1 runs before b2?

Below is full source code section:



    #define COUNTER 10000
      m_value = 0;
      dispatch_queue_t globalQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
      dispatch_queue_t queue = dispatch_queue_create("myqueue", NULL);
      dispatch_group_t group = dispatch_group_create();
       for (int i = 0; i &lt COUNTER; ++i) {
        dispatch_group_async(group, globalQueue, ^() {
          dispatch_async(queue, ^() {
            ++m_value;
          });
        });
      }
      dispatch_group_notify(group, queue, ^() {
        NSLog(@"m_value Actual: %d Expected: %d", m_value, COUNTER);
      });

      dispatch_release(queue);
      dispatch_release(group);
      queue = nil;
      group = nil;
      return YES;

Can we assure m_value == COUNTER always? Thanks

AnkyHe
  • 76
  • 1
  • 6

2 Answers2

3

Blocks submitted to concurrent queues may execute concurrently, however from the Apple docs "Blocks submitted to a serial queue are executed one at a time in FIFO order." The main queue is serial as are any queues that you create with dispatch_create_queue.

Thomas Bouldin
  • 3,707
  • 19
  • 21
  • Awesome, so if we want FIFO we can simply use `dispatch_create_queue`, and set the priority with `dispatch_set_target_queue` [as per this answer](http://stackoverflow.com/a/9965389/72176) :) – William Denniss Nov 24 '12 at 03:43
  • Yes, though I'm not sure you need dispatch_set_target_queue. I rarely see a case where it is correct for a developer to *increase* priority. – Thomas Bouldin Nov 26 '12 at 18:22
  • I used it to _decrease_ priority to the lowest level. I was processing photos using a queue created with `dispatch_create_queue`, and it seemed to help (UI was more responsive). – William Denniss Nov 27 '12 at 01:01
  • 1
    In this case, you might consider the background queue where available (4.3.0 and greater). This is guaranteed to be serial and will wait until foreground activity has settled. – Thomas Bouldin Dec 02 '12 at 23:55
  • Is ```dispatch_queue_create``` instead of ```dispatch_create_queue```? – Lubbo Feb 27 '18 at 10:43
0

according the documentation the blocks (on global queue) could be executed concurrently

"Blocks submitted to these global concurrent queues may be executed concurrently with respect to each other."

Sandeep Chayapathi
  • 1,490
  • 2
  • 13
  • 31