dispatch_sync does two things:

  1. queue a block 
  2. blocks the current thread until the block has finished running

Given that the main thread is a serial queue (which means it uses only one thread), the following statement:

will cause the following events:

  1. dispatch_sync queues the block in the main queue.
  2. dispatch_sync blocks the thread of the main queue until the block finishes executing.
  3. dispatch_sync waits forever because the thread where the block is supposed to run is blocked. 

The key to understanding this is that dispatch_sync does not execute blocks, it only queues them. Execution will happen on a future iteration of the run loop.

The following approach:




I know where your confusion comes from:

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

Careful, it says current thread.

Thread != Queue

A queue doesn't own a thread and a thread is not bound to a queue.

 

 

I found this in the documentation (last chapter):

Do not call the dispatch_sync function from a task that is executing on the same queue that you pass to your function call. Doing so will deadlock the queue. If you need to dispatch to the current queue, do so asynchronously using the dispatch_async function.

Also, I followed the link that you provided and in the description of dispatch_sync I read this:

Calling this function and targeting the current queue results in deadlock.

So I don't think it's a problem with GCD, I think the only sensible approach is the one you invented after discovering the problem.

 https://stackoverflow.com/questions/10984732/why-cant-we-use-a-dispatch-sync-on-the-current-queue
------------------越是喧嚣的世界,越需要宁静的思考------------------ 合抱之木,生于毫末;九层之台,起于垒土;千里之行,始于足下。 积土成山,风雨兴焉;积水成渊,蛟龙生焉;积善成德,而神明自得,圣心备焉。故不积跬步,无以至千里;不积小流,无以成江海。骐骥一跃,不能十步;驽马十驾,功在不舍。锲而舍之,朽木不折;锲而不舍,金石可镂。蚓无爪牙之利,筋骨之强,上食埃土,下饮黄泉,用心一也。蟹六跪而二螯,非蛇鳝之穴无可寄托者,用心躁也。