dispatch_sync() always execute block in main thread - objective-c

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

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 not working with main queue

please consider following code:
dispatch_queue_t myQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_group_t myGroup = dispatch_group_create();
dispatch_group_async(myGroup, myQueue, ^{
NSLog(#"First block of code");
});
dispatch_group_async(myGroup, myQueue, ^{
NSLog(#"Second block of code");
});
dispatch_group_async(myGroup, myQueue, ^{
dispatch_sync(dispatch_get_main_queue(), ^{ //problem here
dispatch_time_t myTime = dispatch_time(DISPATCH_TIME_NOW, 10ull * NSEC_PER_SEC);
dispatch_after(myTime, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSLog(#"Third block of code work");
});
});
});
dispatch_group_wait(myGroup, DISPATCH_TIME_FOREVER);
NSLog(#" All done ?");
Problem is in dispatch_sync(dispatch_get_main_queue(), ^{
When i make dispatch_async(dispatch_get_main_queue(), ^{, it works as it should. Point of making that sync, is blocking main thread for 10 seconds, simulating "hard work". But, unfortunately, its not work. I wonder why?
What i want is: dispatch_sync block main thread for only 10 seconds, then execution continues.
What in fact happening: dispatch sync block whole application from any further execution.
If that code is running on the main event loop, then the dispatch_group_wait() is going to block the main queue. That prevents the synchronous execution of any block on the main queue and leads to deadlock.
You can verify this by pausing into the debugger. You'll likely see the main thread/queue blocked on the call to wait and a secondary thread/queue blocked on dispatch_sync.
Your code is presumably run on the main queue. It dispatches three blocks on the background, then waits until all three blocks have finished running. Since this is done on the main queue, other blocks will only start running on the main queue afterwards, that is after all the three async blocks that you queued up have finished.
Now the third of these three blocks calls the main thread with a sync call. What that means is it adds a block to the main queue, then it waits until the block starts executing, then it waits further until the block finishes executing, then the dispatch_sync call returns to its caller.
Well, that block dispatched to the main thread cannot start executing, because the main thread is busy waiting for the three async blocks to finish, and one of them won't finish because it is waiting for the block dispatched to the main thread to start executing, which it can't because and so on and so on forever. It doesn't actually matter one bit what you are trying to do in the synchronous block, because that block never gets as far as starting to execute.

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

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?????");
});
});

Waiting for asynchronous threads in objective-c

I am trying to wait for asynchronous threads in objective-c without blocking the UI thread (it is an app).
I have the following code:
-(void)MainUIThread
{
[exporter exportAsynchronouslyWithCompletionHandler:^{
dispatch_async(dispatch_get_main_queue(), ^{
[self exportDidFinish:exporter];
//wait here without blocking
});
}];
}
In C# I would use async and await, can I easily achieve this in objective-c?
[exporter exportAsynchronouslyWithCompletionHandler:^{
dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
[self exportDidFinish:exporter]; // Its non blocking process
dispatch_async(dispatch_get_main_queue(), ^(void){
//Update your UI.
});
}];
Try above snippet.
You calling [self exportDidFinish:exporter] method on main thread that why it block your UI. I suppose exportDidFinish method have just a business logic then post that logic calculation in background thread using dispatch_get_global_queue then get it back on main thread using dispatch_get_main_queue().
What makes you think that you should wait for an asynchronous operation to finish? That's the whole point of asynchronous operation, you don't wait for it!
You called exportAsynchronouslyWithCompletionHandler and gave it a block. I don't know that method, but I assume it will do things asynchronously, and when it is finished it will call the block that you give it. The call to exportAsynchronouslyWithCompletionHandler will return very quickly, as soon as the method has set up its asynchronous operation.
That block dispatches another block calling "exportDidFinish:exporter" on the main thread, then it returns (with no reason to wait), then all the asynchronous code in exportAsynchronouslyWithCompletionHandler is finished.
All we have now is one block dispatched to the main queue. As soon as the run loop is idle, that block is executed on the main thread. The commented line that you added "// Wait here" is pointless. exportDidFinish:exporter will be called on the main thread when it's time to be called, and then we are 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.