iDev: How to pause or wait execution until block executes with semaphore in iOS

Hi Friends, 

Todays we discuss some important concept of threads:

If we want any execution to wait or pause until block finishes its execution and frees up the resources, then we have to use dispatch semaphore. A dispatch semaphore works same as regular semaphore. Only one exception is, it takes a lesser amount of time to obtain a dispatch semaphore than it takes with traditional system semaphore when resources are available.

Below are the steps for using a dispatch semaphore:

  1. Create the semaphore using the dispatch_semaphore_create function. If you want to indicate the number of resources available, you can specify the positive integer here.
  2. To wait on the semaphore in each task, call dispatch_semaphore_wait.
  3. Acquire the resource and do your work, when the wait call returns.
  4. Release the resource and signal the semaphore by calling the functiondispatch_semaphore_signal.


Here is the example how these steps works:

Consider you have to insert some data in SQLite DB in background with dispatch_async but at same time you want to wait until this block executes and give you total number of count of inserted data in DB and show it on table. In this case you can use semaphore to stop further execution of code until the block finishes its job. So if you have table reload code after dispatch_async block then it will not execute until dispatch_async finishes its execution.

// Create the semaphore, specifying the initial pool size
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        @autoreleasepool {
                // Write your code here…
            // Fetch data from SQLite DB
// Wait for a block execution
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
// Use fetched data here to reload table.

Drop your comments, if you have any queries.

 Reference Article : Here 

Related resources on Blocks

Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s