GCD

GCD

异步刷新屏幕在主队列中执行

dispatch_async(dispatch_get_main_queue(), ^{
   //更新屏幕代码
   });

dispatch_sync()锁死

NSLog(@"1");
 dispatch_sync(dispatch_get_main_queue(), ^{
  NSLog(@"2"); //阻塞,造成锁死
 });
 NSLog(@"3");

在当前线程中调用dispatch_sync()回造成锁死
dispatch_sync()会做两件事情

  1. 将block加入到queue中
  2. 阻塞当前线程,等待block返回。
    了解了dispatch_sync()做的事情就很明白为什么会被锁死,dispatch_sync()在调用立即阻塞当前线程等待block执行完毕,而block又发现当前线程被阻塞就等着,所以就造成了锁死。

下面是搜到的英文解释。

dispatch_sync does two things:

  • queue a block
  • 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:
dispatch_sync(dispatch_get_main_queue(), ^(){/.../});
will cause the following events:

  • dispatch_sync queues the block in the main queue.
  • dispatch_sync blocks the thread of the main queue until the block finishes executing.
  • 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.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 本篇博客共分以下几个模块来介绍GCD的相关内容: 多线程相关概念 多线程编程技术的优缺点比较? GCD中的三种队列...
    dullgrass阅读 37,931评论 28 236
  • iOS中GCD的使用小结 作者dullgrass 2015.11.20 09:41*字数 4996阅读 20199...
    DanDanC阅读 980评论 0 0
  • GCD为Grand Central Dispatch的缩写。[1] Grand Central Dispatch ...
    sea777777阅读 515评论 0 0
  • 本篇博客共分以下几个模块来介绍GCD的相关内容: 多线程相关概念 多线程编程技术的优缺点比较? GCD中的三种队列...
    有梦想的老伯伯阅读 1,041评论 0 4
  • 肯尼斯正躺在床上。二十五分钟前,他喝下迪卢木多递来的那杯酒,随之而来的便是逐渐模糊的视线和在那一瞬间得知自己被下了...
    獣面阅读 3,336评论 0 2