0

This code is blocking on the call to dispatch_sync. I'm new to dispatch queues. Any reason why this would block?

NSLog(@"%@",dispatch_get_current_queue());
NSLog(@"%@",dispatch_get_main_queue());

if (dispatch_get_current_queue() == dispatch_get_main_queue())
{
    block();
}
else
    dispatch_sync(dispatch_get_main_queue(),block);

The logs print these queues

OS_dispatch_queue_root: com.apple.root.low-priority[0x345bbc0]

OS_dispatch_queue: com.apple.main-thread[0x345b900]>

4

1 回答 1

3

Comparing the current queue against the main queue is not a valid way to check whether you are running on the main thread.

From the GCD docs - http://developer.apple.com/library/mac/#DOCUMENTATION/Darwin/Reference/ManPages/man3/dispatch_get_main_queue.3.html

The result of dispatch_get_main_queue() may or may not equal the result of dispatch_get_current_queue() when called on the main thread. Comparing the two is not a valid way to test whether code is executing on the main thread. Foundation/AppKit programs should use [NSThread isMainThread]. POSIX programs may use pthread_main_np(3).

dispatch_get_current_queue() is deprecated and it was meant for debugging only, so you shouldn't use it in production code.

There's no need to check if this queue is the main queue, just dispatch_sync it on the main queue and it'll get there.

于 2013-07-16T14:44:03.017 回答