Skip to main content

DispatchGroup vs DispatchSemaphore in iOS (Swift)

 In this post, I will share my knowledge about how to synchronise async code in swift programming language. Puzzled? Let read it to clarify :)

In my current project, I had to develop a solution where I need to perform multiple api calls in a loop, but synchronously and application should not freeze.

Initially, I tried with DispatchGroup, but this approach was successful only if I have to run all apis calls asynchronously. Let’s look at below code snippet which illustrate the difference between DispatchGroup and DispatchSemaphore.

DispatchGroup:

In below example, api.performSomeAction() will be executed concurrently.

This method call api in asynchronous manner.

    /// - parameter ids: Array of identifer which will pass to api's post data

    private func insertData(ids: [String]) {

        

        let group = DispatchGroup()

        

        ///Method which will execute when below if loop completes
         // (When dispatch group is notified)

        func completion() {

            //Perform some action in the end

        }

        

        ///All api calls will be parallel.

        for identifier in ids {

            group.enter()

            api.performSomeAction(id: identifier, success: { [weak self] _ in

                group.leave()

             }, failure: { _ in

                group.leave()

            })

        }

        

        group.notify(queue: .main) {

            completion()

        }

    }

DispatchSemaphore

In below example, api.performSomeAction() will be executed sequentially.

   /// This method call api in synchronous manner without blocking the UI

    /// - parameter ids: Array of identifer which will pass to api's post data

    private func insertData(ids: [String]) {

        

        let group = DispatchGroup()

        

        ///Method which will execute when below if loop completes

        func completion() {

            //Perform some action in the end

        }

        

        DispatchQueue.global().async {

            let semaphore = DispatchSemaphore(value: 0)

            

            ///All api calls will be sequential.

            for identifier in ids {

                api.performSomeAction(id: identifier, success: { [weak self] _ in

                    semaphore.signal()

                 }, failure: { (_) in

                    semaphore.signal()

                })

                _ = semaphore.wait(timeout: .distantFuture)

            }

            completion()

        }

    }

Conclusion:

Dispatch Semaphore: A shared resource is not accessed at the same time using semaphore. Dispatch Group: If tasks are independent of one another, use dispatch group.

Comments

  1. You have made your points in a smart way. I am impressed with how interesting you have been able to present this content. Thanks for sharing nice information.

    Graphic Design Courses in South Delhi

    ReplyDelete
  2. Your contents are completely awesome and share worthy. I really appreciate your efforts that you put on this. Keep sharing.

    C++ Training Institute in Delhi

    ReplyDelete
  3. Wow, What an Excellent post. I really found this to much informative. It is what I was searching for. I would like to suggest you that please keep sharing such type of info.ready made wordpress website

    ReplyDelete

Post a Comment

Popular posts from this blog

How to kill/exit iOS application on a button click programmatically

I had been practising below code to kill an iOS application. exit(0); But last week, my application was rejected by app store due to following reason: We found that your app includes a UI control for quitting the app. This is not in compliance with the iOS Human Interface Guidelines, as required by the App Store Review Guidelines . To avoid any such rebuff, suspend the application using following code snippet. UIApplication.shared.perform(#selector(NSXPCConnection.suspend)) Good news is that now my application is passed the  iOS Human Interface Guidelines and live on app store.

Return multiple values from a function in objective C

We can return tuples in swift as follows:- func getData () -> ( Int , Int , Int ) { //...code here return ( hour , minute , second ) } You can't do that in objective-c. Best option is using parameters by reference . Something like this. - ( void ) getHour :( int *) hour minute :( int *) minute second :( int *) second { * hour = 1 ; * minute = 2 ; * second = 3 ; } And use it like this. int a , b , c ; [ self getHour :& a minute :& b second :& c ]; NSLog (@ "%i, %i, %i" , a , b , c );