Preliminary study of iOS multi thread (ten) - dispatch synchronization

Recommended for you: Get network issues from WhatsUp Gold. Not end users.

GCD provides two ways to support the dispatch queue synchronous, namely dispatch group and signal.

A, dispatch group(dispatch group)

1 create dispatch group

dispatch_group_t group = dispatch_group_create(); 

The block association 2 start dispatch in the queue to group

dispatch_group_async(group, queue, ^{ 

  // . . .  

}); 

3 wait for group associated block execution completed, can also set the timeout parameter

dispatch_group_wait(group, DISPATCH_TIME_FOREVER); 

4 the group settings for the notification of a block, when the group associated block after the execution is completed, we call this block. Similar to dispatch_barrier_async.

dispatch_group_notify(group, queue, ^{

  // . . .  

}); 

Running 5 manual management of group associated block (or count), to enter and exit the group number must match

dispatch_group_enter(group);

dispatch_group_leave(group);

So the two of the following calls is in fact equivalent,  

A)

dispatch_group_async(group, queue, ^{ 

  // . . .  

}); 

B) 

dispatch_group_enter(group);

dispatch_async(queue, ^{

  //. . .

  dispatch_group_leave(group);

});

So, you can use the dispatch_group_enter,   dispatch_group_leave and dispatch_group_wait to realize synchronous, specific examples: .


Two, the dispatch signal(dispatch semaphore)

1 create a semaphore signal, can set the number of resources. 0 indicates no resources, calling dispatch_semaphore_wait will wait immediately.

dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);

2 wait for the signal, you can set the timeout parameter. This function returns 0 notice, non 0 timeout.

dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);

3 notification signal, if the waiting thread is awakened returns than 0, otherwise it returns 0.

dispatch_semaphore_signal(semaphore);

Finally, to generate consumer example, use the dispatch is how to realize the synchronization signal:


dispatch_semaphore_t sem = dispatch_semaphore_create(0);

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ //Consumer queue

while (condition) {

    if (dispatch_semaphore_wait(sem, dispatch_time(DISPATCH_TIME_NOW, 10*NSEC_PER_SEC))) //Wait for 10 seconds.

      continue;

    //Get data

  }

});

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ //The producer queue

while (condition) {

     if (!dispatch_semaphore_signal(sem))

    {

      sleep(1); //wait for a while

      continue;

    }

    //Notice of the successful

  }

});


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Posted by Anastasia at November 28, 2013 - 1:52 AM