Why dispatch_sync on main thread cause deadlock but NSBlockOperation doesn't?

250 Views Asked by At

As the title, dispatch_sync() on main queue and main thread will cause deadlock, like that:

dispatch_sync(dispatch_get_main_queue(), ^{
    NSLog(@"%@", [NSThread currentThread]);
});

But NSBlockOperation will not cause deadlock:

NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
    NSLog(@"%@", [NSThread currentThread]);
}];
[operation start];

So, I don't understand why? This function does not return until the block has finished just like dispatch_sync, so why it doesn't cause deadlock? And what's the different between them?

1

There are 1 best solutions below

0
On

As you can read here in the official Documentation for NSBlockOperation:

"Blocks added to a block operation are dispatched with default priority to an appropriate work queue. The blocks themselves should not make any assumptions about the configuration of their execution environment."

That means specifically, that your block will not executed on the main thread.

For concurrent operations (which is true for NSBlockOperation), the method start schedules its work asynchronously. You should have seen in the log, that your block does not execute on the main thread. (Note: you need to ensure the main thread will not finish before the block has been executed in order to see the log.)