串行队列上的dispatch_async和dispatch_sync之间的区别? [英] Difference between dispatch_async and dispatch_sync on serial queue?

查看:707
本文介绍了串行队列上的dispatch_async和dispatch_sync之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个这样的串行队列:

I've created a serial queue like this:

    dispatch_queue_t _serialQueue = dispatch_queue_create("com.example.name", DISPATCH_QUEUE_SERIAL);

dispatch_async 之间的区别是什么?

What's the difference between dispatch_async called like this

 dispatch_async(_serialQueue, ^{ /* TASK 1 */ });
 dispatch_async(_serialQueue, ^{ /* TASK 2 */ });

dispatch_sync 在此序列中调用如下queue?

And dispatch_sync called like this on this serial queue?

 dispatch_sync(_serialQueue, ^{ /* TASK 1 */ });
 dispatch_sync(_serialQueue, ^{ /* TASK 2 */ });

我的理解是,无论使用哪种派遣方式,任务1 将在 TASK 2 之前执行并完成,对吗?

My understanding is that, regardless of which dispatch method is used, TASK 1 will be executed and completed before TASK 2, correct?

推荐答案

是。使用串行队列可确保任务的串行执行。唯一的区别是 dispatch_sync 仅在块完成后返回,而 dispatch_async 在添加到队列后返回可能没有完成。

Yes. Using serial queue ensure the serial execution of tasks. The only difference is that dispatch_sync only return after the block is finished whereas dispatch_async return after it is added to the queue and may not finished.

此代码

dispatch_async(_serialQueue, ^{ printf("1"); });
printf("2");
dispatch_async(_serialQueue, ^{ printf("3"); });
printf("4");

它可能会打印 2413 2143 1234 1 始终在 3之前

It may print 2413 or 2143 or 1234 but 1 always before 3

此代码

dispatch_sync(_serialQueue, ^{ printf("1"); });
printf("2");
dispatch_sync(_serialQueue, ^{ printf("3"); });
printf("4");

它始终打印 1234

注意:对于第一个代码,不会打印 1324 。因为在 printf(2)之后 c> c> printf(3)被调度执行。并且任务只能在分派后执行

Note: For first code, it won't print 1324. Because printf("3") is dispatched after printf("2") is executed. And a task can only be executed after it is dispatched.

执行时间任务不会改变任何事情。此代码始终打印 12

The execution time of the tasks doesn't change anything. This code always print 12

dispatch_async(_serialQueue, ^{ sleep(1000);printf("1"); });
dispatch_async(_serialQueue, ^{ printf("2"); });

可能发生的事情是


  • 线程1:dispatch_async一个耗时的任务(任务1)到串行队列

  • 线程2:开始执行任务1

  • 线程1:dispatch_async另一个任务(任务2)到串行队列

  • 线程2:任务1完成。开始执行任务2

  • 线程2:任务2完成。

  • Thread 1: dispatch_async a time consuming task (task 1) to serial queue
  • Thread 2: start executing task 1
  • Thread 1: dispatch_async another task (task 2) to serial queue
  • Thread 2: task 1 finished. start executing task 2
  • Thread 2: task 2 finished.

你总是看到 12

这篇关于串行队列上的dispatch_async和dispatch_sync之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆