1

Apple's GCD documentation states the following:

GCD provides and manages FIFO queues to which your application can submit tasks in the form of block objects. Blocks submitted to dispatch queues are executed on a pool of threads fully managed by the system. No guarantee is made as to the thread on which a task executes. GCD offers three kinds of queues:

Does this mean that even if I issue a request such as

dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{...});

it could result in the block of code to be executed on the main thread? In that case, it seems that calling dispatch_sync with a concurrent queue on main thread can result in a deadlock situation in which the main thread is stuck waiting for itself.

Is my interpretation of the GCD documentation correct?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
minch
  • 331
  • 3
  • 13

2 Answers2

1

Yes it appears that dispatch_sync to a global queue can mean executing code on the main thread if the caller is on the main thread. The documentation for dispatch_sync explains:

As an optimization, this function invokes the block on the current thread when possible.

dispatch_sync always scheduling a block on Main Thread

Community
  • 1
  • 1
0

Since dispatch_sync waits for the block to finish, it doesn't really make much difference whether the block is executed on a concurrent thread or the main thread; the main thread is blocked anyway.

So calling dispatch_sync from the main thread effectively blocks the main thread until the block is finished and therefore is a bad idea unless the block executes for a short time only.

gnasher729
  • 51,477
  • 5
  • 75
  • 98