Deadlock when calling dispatch_sync() even though it's on another queue - objective-c

I am aware that calling dispatch_async in the current queue will cause a deadlock, however, experiencing a deadlock in a completely different queue:
-(void) deadlock{
// we reach this point in the main queue
dispatch_sync(dispatch_queue_create("lucas", 0), ^{
NSLog(#"Doing something in the bakcgound...");
// We reach this point in another queue, but it deadlocks!
dispatch_sync(dispatch_get_main_queue(), ^{
NSLog(#"Will I ever get here?????");
});
});
}
Any idea of what I'm doing wrong??

Yes, it's a deadlock. Just like you have been creating an example of one
-(void) deadlock{
// we reach this point in the main queue
//and so main queue waits till this task will finish
dispatch_sync(dispatch_queue_create("lucas", 0), ^{
//doing something in background
//while main queue still blocked by that dispatch_sync() call
NSLog(#"Doing something in the bakcgound...");
// We reach this point in another queue, but it deadlocks!
//Of cause it does!!! Main queue is still waiting till task dispatched to "lucas" queue synchronously finishes. But it can't - waits for main queue to perform this later bock synchronously
dispatch_sync(dispatch_get_main_queue(), ^{
NSLog(#"Will I ever get here?????");
});
});
}
//we reach this point only after all code written above will performed. so, in our case, this point is unreachable either way
So, dependently on your task, you should change one of this dispatch_sync() to dispatch_async().

Dispatch_sync is semantically equivalent to a traditional mutex lock, rather than creating a thread. Try the following, will give you: "Is main thread: 1".
dispatch_sync(dispatch_queue_create("lucas", 0), ^{
NSLog(#"Doing something in the bakcgound...");
NSLog(#"Is main thread: %d", [NSThread isMainThread]);
// We reach this point in another queue, but it deadlocks!
dispatch_sync(dispatch_get_main_queue(), ^{
NSLog(#"Will I ever get here?????");
});
});
What you want I think is more or less the following:
dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
NSLog(#"Doing something in the bakcgound...");
dispatch_async(dispatch_get_main_queue(), ^(void){
NSLog(#"Will I ever get here?????");
});
});

Related

ObjectiveC - Avoiding deadlock while synchronous dispatch to main queue from background

Recently I came to a point where I needed some block of code to execute always on the main thread synchronously. This block can be called from any thread. I solved this problem with the code that was already suggested in this SO answer by #Brad Larson
As the comments to this answer it is evident that the deadlock can occur, but I got into the deadlock very very easily. Please have a look at this code.
-(IBAction) buttonClicked
{
// Dispatch on the global concurrent queue async.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
NSString* data = [self getTheString];
NSLog(#"From Background Thread: %#", data);
};
// Dispatch on the main queue async.
dispatch_async(dispatch_get_main_queue(), ^{
NSString* data = [self getTheString];
NSLog(#"From Main Thread: %#", data);
};
}
// This method can be called from any thread so synchronize it.
// Also the code that sets the string variable based on some logic need to execute on main thread.
-(NSString*) getTheString
{
__block NSString* data = nil;
#synchronized(self)
{
// Have some code here that need to be synchronized between threads.
// .......
//
// Create a block to be executed on the main thread.
void (^blockToBeRunOnMainThread)(void) = ^{
// This is just a sample.
// Determining the actual string value can be more complex.
data = #"Tarun";
};
[self dispatchOnMainThreadSynchronously:blockToBeRunOnMainThread];
}
}
- (void) dispatchOnMainThreadSynchronously:(void(^)(void))block
{
if([NSThread isMainThread])
{
if (block)
{
block();
}
}
else
{
dispatch_sync(dispatch_get_main_queue(), ^{
if (block)
{
block();
}
});
}
}
In this piece of code there are two simultaneous asynchronous requests to function getTheString (Assume you have no control over the buttonClicked method and how it calls getTheString api) . Suppose the request from global queue comes first and it is trying to run the block on the main thread synchronously, till that time background thread in waiting for main thread to execute the block synchronously, at the same time request from main queue comes and trying the acquire the lock from background thread, but as background thread in not complete main thread waiting for background thread to complete. Here we have a deadlock on main thread as main thread waiting for background thread to finish, and background thread is waiting for main thread to execute block.
If I remove the #synchronize statement everything works fine as expected. May be I don't need a #synchronize statement here but in same case you may need to have this. Or it can even happen from some other parts of the code.
I tried to search the whole net for the solution and also tried dispatch_semaphore but couldn't solve the issue. May be I am just not doing things the right way.
I assume this is classic problem of deadlock and faced by developers again and again, and probably have solved it to some extent. Can anyone help with this, or point me to right direction?
I would create a synchronous queue (NSOperationQueue would be simplest) and submit the block to be run on the main thread to that queue. The queue would dispatch the blocks in the order received, maintaining the ordering you desire. At the same time, it disassociates the synchronicity between calling the getTheString method and the dispatch to the main thread.

dispatch_sync() always execute block in main thread

Is there any difference between if dispatch_sync is called in 3 different queue like
1.
dispatch_sync(dispatch_get_main_queue(),^(void){
NSLog(#"this execute in main thread") // via [NSThread isMainThread]
});
2.
dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^(void){
NSLog(#"this also execute in main thread") // via [NSThread isMainThread]
}
3.
dispatch_queue_t queue;
queue = dispatch_queue_create("com.example.MyQueue", NULL);
dispatch_sync(queue, ^(void){
NSLog(#"this also execute in main thread") // via [NSThread isMainThread]
}
Whenever i call dispatch_sync, block executed in main thread, without considering in which queue it is dispatched. So why this function take queue as a argument as it doesn't use it. Can someone please clarify this?
dispatch_sync is a blocking operation. That is, the function will not return until the work represented in the block is completed.
When dispatched to an asynchronous queue -- like one of the global queues or a concurrent queue of your own making -- there is no reason to do anything but invoke the block on the thread that called dispatch_sync(). Even in the case of invoking the block on a synchronous queue, the dispatch_sync() is going to wait until completion anyway so, internally, it might as well stop until the rest of the work is done in the queue and then execute the block directly.
As it turns out, passing data from thread A to thread B is expensive. If the queue is in the state where execution can happen immediately, then dispatch_sync will fast path the execution by simply calling the block on the thread that dispatch_sync was called on.
And, by definition, you shouldn't care. The calling thread is blocked -- can't do a thing -- until dispatch_sync() returns.
So, really, all of this is an implementation detail. GCD is free to execute the blocks on whatever threads it deems most appropriate. It just so happens that don't context switch is often the most important rule of figuring that out.
See dispatch_sync documentation, which notes
As an optimization, this function invokes the block on the current thread when possible.
If you dispatch something synchronously, since the thread must wait for the dispatched code to complete, anyway, it will frequently run that code on the current thread. So if dispatched synchronously from the main thread, it will run on main thread. If dispatched synchronously from a background thread, it will run on that background thread.
As noted by ipmcc, a well-known exception is when a background thread dispatches something synchronously to the main thread. As the libdispatch source says:
It's preferred to execute synchronous blocks on the current thread
due to thread-local side effects, garbage collection, etc. However,
blocks submitted to the main thread MUST be run on the main thread.
For your problem: you call the dispatch_sync always in main queue, and if you wanna know why, see the following:
At first you need to pay attention to the description on of "dispatch_sync"
Submits a block to a dispatch queue for synchronous execution. Unlike dispatch_async,
this function does not return until the block has finished.
Calling this function and targeting the current QUEUE(NOT THREAD) results in deadlock.
#define logStep(step,queue) NSLog(#"step: %d at thread: %# in -- queue: %s",step,[NSThread currentThread],dispatch_queue_get_label(queue));
// call the method in main thread within viewDidLoad or viewWillAppear ...
- (void)testDispatchSync{
//let's distinctly tell the 4 queues we often use at first
self.concurrentQ = dispatch_queue_create("com.shared.concurrent", DISPATCH_QUEUE_CONCURRENT);
self.serialQ = dispatch_queue_create("com.shared.serial", DISPATCH_QUEUE_SERIAL);
dispatch_queue_t mainQ = dispatch_get_main_queue();
dispatch_queue_t globalQ = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
logStep(1,mainQ) //we're in main thread and main queue, current queue IS main queue
// do a sync in main thread & concurrent queue
dispatch_sync(_concurrentQ, ^{
logStep(2,_concurrentQ)
});
// do a sync in main thread & serial queue
dispatch_sync(_serialQ, ^{
logStep(3,_serialQ)
});
//uncommenting the following code that you'wll see a crash will occur, because current queue is main queue
// dispatch_sync(mainQ, ^{
// logStep(4, mainQ)
// });
dispatch_async(_concurrentQ, ^{
// inside of the this scope, current queue is "_concurrentQ"
logStep(11,_concurrentQ)
// using sync in any queue here will be safe!
dispatch_sync(_concurrentQ, ^{
logStep(12,_concurrentQ)
});
dispatch_sync(_serialQ, ^{
logStep(13,_concurrentQ)
});
dispatch_sync(mainQ, ^{
logStep(14,mainQ)
});
dispatch_sync(globalQ, ^{
logStep(15,globalQ)
});
// using async in any queue here will be safe!
dispatch_async(_concurrentQ, ^{
logStep(111,_concurrentQ)
});
dispatch_async(_serialQ, ^{
logStep(112,_concurrentQ)
});
dispatch_async(mainQ, ^{
logStep(113,mainQ)
});
dispatch_async(globalQ, ^{
logStep(114,globalQ)
});
});
dispatch_async(_serialQ, ^{
// inside of the this scope, current queue is "_serialQ"
logStep(21,_serialQ)
// using async in any queue except current queue here will be safe!
dispatch_sync(_concurrentQ, ^{
logStep(22,_concurrentQ)
});
dispatch_sync(mainQ, ^{
logStep(23,mainQ)
});
dispatch_sync(globalQ, ^{
logStep(24,globalQ)
});
//uncommenting the following code that you'wll see a crash will occur, because current queue is "_serialQ"
// dispatch_sync(_serialQ, ^{ //app will die at here
// logStep(25,_serialQ)
// });
});
}
So we got the conclusion:
the key problem is that thread will be blocked while "dispatch_sync" running on current queue which is a serial queue at the same time.
main queue is also a serial queue so that it explained why you cann't call dispatch_sync in main thread

How to wait past dispatch_async before proceeding?

I have a series of dispatch_async that I am performing and I would like to only update the UI when they are all done. Problem is the method within dispatch_async calls something in a separate thread so it returns before the data is fully loaded and dispatch_group_notify is called before everything is loaded.
So I introduce a infinite loop to make it wait until a flag is set.
Is this the best way? See code below.
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0);
dispatch_group_t group = dispatch_group_create();
for (...) {
dispatch_group_async(group, queue, ^{
__block BOOL dataLoaded = NO;
[thirdPartyCodeCallWithCompletion:^{
dataLoaded = YES;
}];
// prevent infinite loop
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)),
queue, ^{
dataLoaded = YES;
});
// infinite loop to wait until data is loaded
while (1) {
if (dataLoaded) break;
}
}
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
//update UI
});
}
You're already aware of dispatch groups. Why not just use dispatch_group_wait(), which includes support for a timeout? You can use dispatch_group_enter() and dispatch_group_leave() rather than dispatch_group_async() to make the group not done until the internal block for the third-party call with completion is finished.
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0);
dispatch_group_t group = dispatch_group_create();
for (...) {
dispatch_group_enter(group);
dispatch_async(queue, ^{
[thirdPartyCodeCallWithCompletion:^{
dispatch_group_leave(group);
}];
}
}
dispatch_group_wait(group, dispatch_time(DISPATCH_TIME_NOW, NSECS_PER_SEC));
dispatch_async(dispatch_get_main_queue(), ^{
//update UI
});
The use of dispatch_group_wait() does make this code synchronous, which is bad if run on the main thread. Depending on what exactly is supposed to happen if it times out, you could use dispatch_group_notify() as you were and use dispatch_after() to just updates the UI rather than trying to pretend the block completed.
Update: I tweaked my code to make sure that "update UI" happens on the main queue, just in case this code isn't already on the main thread.
By the way, I only used dispatch_async() for the block which calls thirdPartyCodeCallWithCompletion: because your original used dispatch_group_async() and I wasn't sure that the hypothetical method was asynchronous. Most APIs which take a completion block are asynchronous, though. If that one is, then you can just invoke it directly.
Another method is to use semaphore and the dispatch_semaphore_wait:
// Create your semaphore, 0 is specifying the initial pool size
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
#autoreleasepool {
// Your code goes here
}
// Release the resource and signal the semaphore
dispatch_semaphore_signal(semaphore);
});
// Wait for the above block execution, AKA Waits for (decrements) a semaphore.
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
// After this line you can now safely assert anything you want regarding the async operation since it is done.

Prevent a block from running until all previous queue items have completed

Is it possible to add a block to the end of the current queue, and make sure that this block gets called after all existing items in the queue?
The code below doesn't seem to work:
- (void)someTaskWillBeDoneOnThisThreadLater {
// The current scope is a delegate method of a library I'm using,
// and unfortunately the required task gets executed after this delegate
// method is called.
// wait for current queue to be done with everything, including the current scope
dispatch_async(dispatch_get_current_queue(), ^{
// After everything is done, then call the main thread
dispatch_async(dispatch_get_main_queue(), ^{
// Perform some task on main thread
});
});
}
EDIT:
The following code fixed the problem, but I really don't want to rely on 1 second delay. I rather find a better solution.
dispatch_async(dispatch_get_global_queue(0, 0), ^{
dispatch_async(dispatch_get_main_queue(), ^{
sleep(1);
// Perform something on main thread
});
});
I think problem is that you need private queue to get this work. This code:
dispatch_async(dispatch_get_global_queue(0, 0), ^{
NSLog(#"FIRST");
dispatch_async(dispatch_get_current_queue(), ^{
NSLog(#"LAST");
dispatch_async(dispatch_get_main_queue(), ^{
// ...
});
});
sleep(2);
NSLog(#"SECOND");
});
Gives:
2012-07-31 22:57:20.005 Objective-C App[22526:1703] FIRST
2012-07-31 22:57:20.009 Objective-C App[22526:2003] LAST
2012-07-31 22:57:22.010 Objective-C App[22526:1703] SECOND
Which isn't what you wanted. Even dispatch_barrier_async won't help. But when you use private queue:
dispatch_queue_t queue = dispatch_queue_create("test", 0);
dispatch_async(queue, ^{
NSLog(#"FIRST");
dispatch_async(queue, ^{
NSLog(#"LAST");
dispatch_async(dispatch_get_main_queue(), ^{
// ...
});
});
sleep(2);
NSLog(#"SECOND");
});
Will give you result you wanted:
2012-07-31 23:04:41.882 Objective-C App[22564:1703] FIRST
2012-07-31 23:04:43.887 Objective-C App[22564:1703] SECOND
2012-07-31 23:04:43.889 Objective-C App[22564:1703] LAST
As you see "LAST" will be printed at the end and it'll wait 2 seconds until block already on queue is finished.
Although it's not clear that the actual problem is as you've described, there is a facility in GCD, available starting in OS X 10.7 or iOS 4.3 to achieve this: dispatch_barrier_async().
Submitting a Block to a queue using this function causes that Block to wait to execute until all previous Blocks have completed; likewise all subsequent Blocks wait for the barrier to complete.
Note that this is only relevant for concurrent queues, since the nature of a serial queue is that it will not start executing any Block until all previously submitted Blocks have completed.
From the dispatch_barrier_async documentation:
... When the barrier block reaches the front of a private concurrent
queue, it is not executed immediately. Instead, the queue waits until
its currently executing blocks finish executing. At that point, the
barrier block executes by itself. Any blocks submitted after the
barrier block are not executed until the barrier block completes.
So replacing dispatch_async by dispatch_barrier_async in your code should do what you want.
EDIT:
This works only on private (concurrent) queues, see also the #Johnnywho's answer and the following comments.
I overlooked that part of the documentation, sorry.

Wait until background selector is complete to call new method

I'm trying to perform the acquisition of data from the internet on the load of my view. To not lag the UI, I'm performing the HTML download and parsing by using
[self performSelectorInBackground:#selector(alertThreadMethod) withObject:nil];
which checks to see if there is an alert online. In order to display the information on the view however, iOS says that I need to use the main thread. So i call the display code right after:
[self performSelectorInBackground:#selector(alertThreadMethod) withObject:nil];
[self loadAlert];
In doing this, the [self loadAlert]; actually runs before the selector in the background (it is faster). Because of this, it does not have the information that the selector in the background is supposed to provide it.
How can I ensure that [self loadAlert]; runs after? Or is there a better way to do this?
You can either move loadAlert invocation into the alertThreadMethod or use Grand Central Dispatch serial queues, e.g.,
dispatch_queue_t queue = dispatch_queue_create("com.example.MyQueue", NULL);
dispatch_async(queue, ^{
[self alertThreadMethod];
[self loadAlert];
});
dispatch_release(queue);
Or, if loadAlert is updating the UI, since you do UI updates in the main queue, you'd do something like:
dispatch_queue_t queue = dispatch_queue_create("com.example.MyQueue", NULL);
dispatch_async(queue, ^{
[self alertThreadMethod];
dispatch_async(dispatch_get_main_queue(), ^{
[self loadAlert];
});
});
dispatch_release(queue);
By the way, if you're just doing this one task in background, rather than creating your own serial queue, you might just use one of the existing background queues. You only need to create a queue if you need the serial nature (i.e. you're going to be numerous dispatch_async calls and you can't have them running concurrently). But in this simple case, this might be even a little more efficient, bypassing the creating and releasing of the serial queue:
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
[self alertThreadMethod];
dispatch_async(dispatch_get_main_queue(), ^{
[self loadAlert];
});
});
In your alertThreadMethod, after you have your information, call the method performSelectorOnMainThread:withObject:waitUntilDone: and pass it a selector to your loadAlert method.
-(void)alertThreadMethod
{
// get your information here
performSelectorOnMainThread:#selector(loadAlert) withObject:nil waitUntilDone:NO
}