Difference between dispatch_async and dispatch_sync on serial queue?

后端 未结 3 1397
无人及你
无人及你 2020-11-28 00:52

I\'ve created a serial queue like this:

    dispatch_queue_t _serialQueue = dispatch_queue_create(\"com.example.name\", DISPATCH_QUEUE_SERIAL);
3条回答
  •  孤城傲影
    2020-11-28 01:16

    The difference between dispatch_sync and dispatch_async is simple.

    In both of your examples, TASK 1 will always execute before TASK 2 because it was dispatched before it.

    In the dispatch_sync example, however, you won't dispatch TASK 2 until after TASK 1 has been dispatched and executed. This is called "blocking". Your code waits (or "blocks") until the task executes.

    In the dispatch_async example, your code will not wait for execution to complete. Both blocks will dispatch (and be enqueued) to the queue and the rest of your code will continue executing on that thread. Then at some point in the future, (depending on what else has been dispatched to your queue), Task 1 will execute and then Task 2 will execute.

提交回复
热议问题