I'm trying to use a method from a class I downloaded somewhere. The method executes in the background while program execution continues. I do not want to allow program execution to continue until this method finishes. How do I do that?
When using an Executor, we can shut it down by calling the shutdown() or shutdownNow() methods. Although, it won't wait until all threads stop executing. Waiting for existing threads to complete their execution can be achieved by using the awaitTermination() method.
If cancel property is set/Yes then call [Thread exit] in that background thread code and release all the memory allocated by that thread to protect memory leaks (autorelease pool will not take care here for freeing the resources). This is How i resolved the problem.
The wait() is used for inter-thread communication while the join() is used for adding sequencing between multiple threads, one thread starts execution after first thread execution finished.
For a thread to call wait() or notify(), the thread has to be the owner of the lock for that object. Otherwise, a runtime error occur and the rest of code is not executed.
Here's another way to do it using GCD:
- (void)main
{
[self doStuffInOperations];
}
- (void)doStuffInGCD
{
dispatch_group_t d_group = dispatch_group_create();
dispatch_queue_t bg_queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_group_async(d_group, bg_queue, ^{
[self doSomething:@"a"];
});
dispatch_group_async(d_group, bg_queue, ^{
[self doSomething:@"b"];
});
dispatch_group_async(d_group, bg_queue, ^{
[self doSomething:@"c"];
});
// you can do this to synchronously wait on the current thread:
dispatch_group_wait(d_group, DISPATCH_TIME_FOREVER);
dispatch_release(d_group);
NSLog(@"All background tasks are done!!");
// **** OR ****
// this if you just want something to happen after those are all done:
dispatch_group_notify(d_group, dispatch_get_main_queue(), ^{
dispatch_release(d_group);
NSLog(@"All background tasks are done!!");
});
}
- (void)doSomething:(id)arg
{
// do whatever you want with the arg here
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With