Mulithreading: executing method calls only after finished executing other method - ios

I am trying to process method asynchronously, as per requirements, once the first method has completed, only then the second method should start executing. The Problem is first method itself has code that runs on background thread.
I tried dispatch_semaphore_wait, but that didnt work either.
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0);
dispatch_group_t group = dispatch_group_create();
dispatch_group_async(group, queue, ^{
[self firstMethod];
NSLog(#"firstMethod Done");
});
dispatch_group_notify(group, queue, ^ {
NSLog(#"1st method completed");
NSLog(#"2nd method starting");
[self secondMethod];
});
FirstMethod itself runs on another worker thread like this
-(void)firstMethod
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
//processing here.....
}];
What is the best way to achieve it, I cannot change the definition of firstMethod as it provided by some 3rd party and also changing it means changing lots of existing code from where this method is being called

You can use a completion block. You just need to modify firstMethod this way:
- (void)firstMethodWithOnComplete:(void (^)(void))onComplete {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
//processing here.....
onComplete();
});
}
And then use it this way:
[self firstMethodWithOnComplete:^{
[self secondMethod];
}];

Dispatch a Single Queue and call your Methods in order
dispatch_group_async(group, queue, ^{
[self firstMethod];
NSLog(#"firstMethod Done");
[self secondmethod];
});
Or you might dispatch a group of 3 concurrent queues(This is a Wild guess)

Related

Issue in execute a method after completion of another method - iOS

I have two methods as loadTopicPostsFromDB and loadTopicPosts. In the loadTopicPostsFromDB method I am updating the value of a global NSString called strLastTimeStamp which should use in the loadTopicPosts. Thus, I want to execute loadTopicPostsFromDB first and after it finished(global string updated) I want to execute loadTopicPosts method.
This is how I did it. But, currently loadTopicPosts method executes before updating the global strLastTimeStamp, so always I get a wrong strLastTimeStamp.
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_group_t group = dispatch_group_create();
dispatch_group_async(group, queue, ^{
[self performSelectorOnMainThread:#selector(loadTopicPostsFromDB) withObject:nil waitUntilDone:NO];
});
dispatch_group_notify(group, queue, ^{
NSLog(#"LoadDBCompleted");
[self loadTopicPosts];
});
How can I do this, please advice me on what is the wrong in this implementation.
performSelectorOnMainThread: is finished as soon as iOS has put the task into a queue. The selector has most likely not even started running when the call returns. And really, you shouldn't be using performSelectorOnMainThread at all - the function isn't available in Swift, for good reason. The solution is a lot easier (fix the problems yourself):
dispatch_async (dispatch_get_main_queue (), ^{
[self loadTopicsFromDB];
[self loadTopicPosts];
});
You probably want to perform loadTopicsFromDB on a background thread though.
When you are doing something using network connection I advice you to use blocks to handle the endpoint of the call.
It is pretty simple to write in this code
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[self loadTopicsFromDB: ^(BOOL success, NSError *error) {
[self loadTopicPosts];
}];
});

Dispatch_sync or completion block difference in objective-c

I'm struggling with GCD and blocks. I'm trying to create a series of methods that require data from a previous one. I was thinking about 2 different ways to achieve it.
dispatch_sync serial queue
nested completion blocks
Don't you think the following 2 options return the same value? AS far as I read in Apple's dispatch queues, DISPATCH_QUEUE_SERIAL runs in FIFO order. So both options should return identical values.
What am I doing wrong here? and which one is the best approach?
Thanks for your help!
//Option 1
dispatch_queue_t delete_queue = dispatch_queue_create("delete_queue", DISPATCH_QUEUE_SERIAL);
dispatch_sync(delete_queue, ^{
[self dosomething];
});
dispatch_sync(delete_queue, ^{
[self dosomething2];
});
dispatch_sync(delete_queue, ^{
[self dosomething3];
});
//Option 2
-(void)dosomething1:(dispatch_block_t)completion;
-(void)dosomething2:(dispatch_block_t)completion;
-(void)dosomething3:(dispatch_block_t)completion;
[self dosomething:^{
[self dosomething2:^{
[self dosomething3:^{}];
}];
}];
-(void)dosomething:(dispatch_block_t)completion {
/*method logic here*/
completion();
}
-(void)dosomething2:(dispatch_block_t)completion {
/*method logic here*/
completion();
}
-(void)dosomething3:(dispatch_block_t)completion {
/*method logic here*/
completion();
}
Both code samples you have shown are equivalent to just:
[self dosomething];
[self dosomething2];
[self dosomething3];
In other words, both ways execute the methods synchronously, in order, and block the thread until they are done.
Also, as Ken Thomases said, none of your methods "return" anything, so your question about returning doesn't make sense.
It doesn't really make sense to do three separate calls to dispatch_sync() here:
dispatch_sync(delete_queue, ^{
[self dosomething];
});
dispatch_sync(delete_queue, ^{
[self dosomething2];
});
dispatch_sync(delete_queue, ^{
[self dosomething3];
});
You should instead just do them all in a single block:
dispatch_sync(delete_queue, ^{
[self dosomething];
[self dosomething2];
[self dosomething3];
});
As for the use of completion blocks, you can certainly obtain a similar result, except that the completion-handler result would need to be asynchronous.
I think you need to take a step back and explain what kind of API you are trying to design in order to determine how you want to use the tools of the system and language to achieve that API design.

Objective-C - Wait for call on another thread to return before continuing

In my iOS application, I have a database call that takes some time to complete. I have a spinner visible on the screen while this operation is taking place. I am hitting an error with the app crashing with "com.myapp failed to resume in time" so it seems like it is running the database call on the main thread, causing issues.
Current Code
-(void)timeToDoWork
{
...
[CATransaction flush];
[[DatabaseWorker staticInstance] doWork];
//Additional UI stuff here
...
if([self->myReceiver respondsToSelector:self->myMessage])
{
[self->myReceiver performSelector:self->myMessage];
}
}
To get the doWork function to take place on a background thread, it looks like I can use Grand Central Dispatch:
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
[[DatabaseWorker staticInstance] doWork];
});
However, how do I prevent the execution from continuing until it is complete? Should I end the method after the doWork call, and move everything below it to a new function?
Sample
-(void)timeToDoWork
{
...
[CATransaction flush];
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
[[DatabaseWorker staticInstance] doWork];
dispatch_async(dispatch_get_main_queue(), ^{
[self doneDoingWork];
});
});
}
-(void)doneDoingWork
{
//Additional UI stuff here
...
if([self->myReceiver respondsToSelector:self->myMessage])
{
[self->myReceiver performSelector:self->myMessage];
}
}
Is there a better way to do this?
Prevent execution in main thread from continuing is really bad idea. iOS will terminate your application since main thread should always work with run loop.
I suggest you following way to handle your problem:
Write a "Locker". Let it show some view with animated spinner and no buttons at all.
When you start dispatch async operation just bring it to the front and let it work with run loop.
When your async operation completes close the locker.
You can also use blocks.
e.g..
- (void)doWorkWithCompletionHandler:(void(^)())handler {
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
// do your db stuff here...
dispatch_async(dispatch_get_main_queue(), ^{
handler();
});
});
}
And then use it like that:
[[DatabaseWorker staticInstance] doWorkWithCompletionHandler:^{
// update your UI here, after the db operation is completed.
}];
P.S.
It might be a good idea to copy the handler block.
The error you are receiving suggests that you are doing something in application:didFinishLaunchingWithOptions: or applicationDidBecomeAction: or somewhere else in the launch cycle that is taking too long and the app is getting terminated by the launch watchdog timer. Above all, it is vital that you return as quickly as possible from these methods. I'm not sure where your code fits into the launch cycle; but this explanation seems plausible.
There are all sorts of ways to address this; but taking the lengthy process off the main queue is the first step as you noted. Without knowing more about what main queue objects (e.g. UI) depend on this database transaction, I'd say that your suggested solution is perfectly fine. That is, dispatch the work to a background queue; and on completion dispatch the remaining UI work to the main queue.
Delegates were suggested elsewhere as a solution. That's also workable although you still have to concern yourself with which queue the delegate methods get called on.
I think that you should use a delegate in your DatabaseWorker and the method doWork always run in background, so when the worker finish the work it tell to its delegate that the work is finished. The delegate method must be called in the main thread.
In the case that you have many objects that need to know when the DatabaseWorker finish instead to use a delegate I would use notifications.
EDIT:
In the DatabaseWorker class you need to implement the method doWork like this:
- (void) doWork{
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
//Do the work.
dispatch_async(dispatch_get_main_queue(), ^{
[self.delegate finishWork];
});
});
}
And in the class that implement timeTodoWork:
-(void)timeToDoWork
{
...
[CATransaction flush];
[[DatabaseWorker staticInstance] setDelegate:self];
[[DatabaseWorker staticInstance] doWork];
}
#pragma mark DatabaseWorkerDelegate
- (void) finishWork{
//Additional UI stuff here
...
if([self->myReceiver respondsToSelector:self->myMessage])
{
[self->myReceiver performSelector:self->myMessage];
}
}
Also you can use:
[self performSelectorInBackground:#selector(doWorkInBackground) withObject:nil];
instead of:
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
//Do the work.
});
And add a method:
- (void) doWorkInBackground{
//Do the work
[self.delegate performSelectorOnMainThread:#selector(finishWork) withObject:nil waitUntilDone:NO];
}

How to dispatch_group_wait for dispatch_group_async inside an asynchronous block

I have code that looks something like this:
[SVProgressHUD show];
[imageGenerator generateCGImagesAsynchronouslyForTimes:times
completionHandler:^(CMTime requestedTime, ...) {
dispatch_group_async(queueGroup, queue, ^{
// Do stuff
});
}];
dispatch_group_wait(queueGroup, DISPATCH_TIME_FOREVER);
[SVProgressHUD dismiss];
Basically, display a loading animation HUD and start generating image thumbnails from an asset, then once it's done hide the HUD. I'm using a dispatch group since i want to make sure all the thumbnails are generated before i hide the HUD.
But when i run it, the HUD gets dismissed immediately. I'm guessing this is because of the asynchronous nature of the generateCGImagesAsynchronouslyForTimes: completionHandler:--dispatch_group_wait is called before the first dispatch_group_async inside the completionHandler.
What is a graceful way to get around this situation? Thanks.
Think of this method as a static counter available to threads, so when you enter a group the counter increments, and when that block returns, decrements...
When that counter is 0, it will call a block to invoke
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_group_t group = dispatch_group_create();
while(someCondition)
{
dispatch_group_enter(group);
[SomeClassThatLoadsOffTheInternet getMyImages:^{
// do something with these.
dispatch_group_leave(group);
});
}
dispatch_group_notify(group, queue, ^{
// do something when all images have loaded
});
Is that what you were thinking of?

iOS: How to do hard work with data in background thread?

I have a method like:
- (BOOL)shouldDoSomeWork {
BOOL result = // here I need do hard work with data in background thread and return result, so main thread should wait until the data is calculated and then return result;
return result;
}
How to implement that?
Are you looking for this:
-(void) startWork
{
//Show activity indicator
[NSThread detachNewThreadSelector:#selector(doSomeWork) toTarget:self withObject:nil];
}
-(void) doSomeWork
{
NSAutoreleasePool *pool = [NSAutoreleasePool new];
//Do your work here
[pool release];
[self performSelectorOnMainThread:#selector(doneWork) withObject:nil waitUntilDone:NO];
}
-(void) doneWork
{
//Hide activity indicator
}
Example how to do it with GCD:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// Your hard code here
// ...
//BOOL result = ...
dispatch_async(dispatch_get_main_queue(),^{
[self callbackWithResult:result]; // Call some method and pass the result back to main thread
});
});
That's not typically how you would do it. You need something structured more like this:
- (void)doSomeWorkAndThen:(^void)block {
dispatch_async(dispatch_get_global_queue(0, 0), ^ {
// do
// some
// work
dispatch_sync(dispatch_get_main_queue(), ^ {
block();
});
});
That is, you keep the request and what you do afterwards in one place.
Common advice is to use the highest level of abstraction available to you to perform a task. As such NSThread should be relatively low down in the list of things you can do to execute work in the background.
The order you investigate APIs should be like this:
NSOperation / NSOperationQueue
Grand Central Dispatch (libdispatch)
NSThread
POSIX threads
With the first two you write your code as a "unit of work" and then put this work on a queue to be executed at some point. The system takes care of creating and destroying threads for you and the APIs are easy to work with. Here's an example using NSOperationQueue.
NSBlockOperation * blockOperation = [NSBlockOperation blockOperationWithBlock:^{
//Do work
//update your UI on the main thread.
[self performSelectorOnMainThread:#selector(workDone:) withObject:workResults waitUntilDone:NO];
}];
[self.operationQueue addOperation:blockOperation];
easy as that.

Resources