Jab
Jab

Reputation: 929

Make asynchronous method synchronous

Inside dispatch_async() I'm running the next code to upload images. The script uploads all the images at the same time causing the CPU running at 100%. I want to upload the images one by one but can't figure out how. I tried using the following code:

dispatch_group_t group = dispatch_group_create(); 
dispatch_group_enter(group)
dispatch_group_leave(group)
dispatch_group_wait(group, DISPATCH_TIME_FOREVER);

but this freezes the main thread aswell.

The code that uploads the images:

    for imageObj in receiptImageObjList {

        api.uploadImage(imageObj){ status, message, json in

            if(status == true){
                var images = json!["data"]["images"].arrayValue

                cdm.imageFromApi(imageObj, jsonData: images.last!)
                if(imageObj.fileName != nil){
                    var fileManager = FileManager()
                    fileManager.deleteImage(imageObj.fileName!)
                }
            }
        }


    }

Upvotes: 2

Views: 1289

Answers (1)

gnasher729
gnasher729

Reputation: 52632

You should create a dispatch_semaphore_t with a count of let's say six. Before each upload starts, you call dispatch_semaphore_wait, and when the upload has finished (uses no CPU time anymore) you call dispatch_semaphore_signal. Make sure that whatever happens, a call to dispatch_semaphore_signal will happen after dispatch_semaphore_wait is called.

The effect is that you will not make more than six upload calls simultaneously; the 7th call will wait without spending any CPU time until some call finishes and calls signal. Apart from that, there will be no change in your program's behaviour. Except the "for image in" loop will not be finished within a millisecond, because it will be waiting for signals to the semaphore, so you better run the whole thing on a background thread. The number six can obviously replaced with any other number.

But just saying: Using 100% CPU isn't bad if the CPU does useful work. It's only bad if 90% of that 100% is wasted.

Upvotes: 1

Related Questions