Reputation: 21808
Take a look at this code:
dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, nil), ^
{
NSLog(@"DISPATCH_QUEUE");//executed
//never goes further
dispatch_sync(dispatch_get_main_queue(), ^
{
NSLog(@"MAIN_QUEUE");
});
NSLog(@"END OF DISPATCH QUEUE");
});
I expected this code to run as usual program flow but it always puts in console words DISPATCH_QUEUE
and never goes further. The program just stops. Can anyone give an explanation why it behaves this way? What's happening behind the scenes that makes it stop?
Upvotes: 1
Views: 120
Reputation: 8066
dispatch_sync
runs a block on a given queue and waits for it to complete. In this case, the queue is the main dispatch queue. The main queue runs all its operations on the main thread, in FIFO (first-in-first-out) order. That means that whenever you call dispatch_sync, your new block will be put at the end of the line, and won't run until everything else before it in the queue is done.
The problem here is that the block you just enqueued is at the end of the line waiting to run on the main thread, but probably your above code is currently running on the main thread. The block at the end of the queue can't get access to the main thread until the current method finishes using the main thread. so only dispatch_async
works here.
Upvotes: 2
Reputation: 2193
You've probably got a deadlock situation; assuming your first call to dispatch_sync
is coming from the main thread.
In that case, the main thread is waiting for the first dispatch to finish, but inside that block, you're trying to dispatch back to the main thread... deadlock.
It seems that you're trying to:
If that's right, you probably want to be using NSOperation...
Upvotes: 2
Reputation:
You have a deadlock here if you run this code from the main queue (which I assume). The main queue gets blocked until your block from the first call to dispatch_sync
finishes. But inside this block you wait for another block to finish on the main queue which cannot be executed until the outer block finishes since the main queue is a serial queue.
You need to change one of the calls to dispatch_async
.
Upvotes: 3