Using DispatchSemaphore to control asynchronous resources

A counting semaphore is a way of controlling access to a resource from multiple contexts. It can be also a solution for handling asynchronous methods in command line utilities.

I was making a command line utility to access REST APIs recently. I needed a way to make sure that the API calls did respond before the execution of the command was finished. I decided to use a DispatchSemaphore in Swift to take control of the situation.

I initialized the semaphore with a value of 0. Then I called semaphore.wait() just before the return statement from the method. It waits for a signal to occur before continuing execution further. I called semaphore.signal() from the completion handler of the asynchronous code.

The result is that the method can return only after the session.dataTask has finished working.

Avoid blocking the current queue

Calling on wait() would block the current execution queue. That’s why I created a new queue for the dataTask.