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)