考察点

  • 死锁如何形成

    死锁:串行队列+同步执行

  • 由队列循环等待引起的死锁

  • 同步提交的任务,也会在当前线程执行

串行队列 + 同步,会死锁,(主要针对在同一queue队列中)

  1. - (void)test1 {
  2. dispatch_queue_t queue = dispatch_queue_create("serial", DISPATCH_QUEUE_SERIAL);
  3. NSLog(@"1");
  4. dispatch_async(queue, ^{
  5. NSLog(@"2");
  6. dispatch_sync(queue, ^{
  7. NSLog(@"3");
  8. });
  9. NSLog(@"4");
  10. });
  11. NSLog(@"5");
  12. }
  13. 2020-12-26 15:15:30.063692+0800 dd[21630:5252182] 1
  14. 2020-12-26 15:15:30.063937+0800 dd[21630:5252182] 5
  15. 2020-12-26 15:15:30.063951+0800 dd[21630:5252264] 2
  16. 出现死锁奔溃现象:
  17. ---------------------------------------------------------------
  18. Thread 3: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)

**
假设换成并发队列,依旧有同步任务,不会死锁

  1. - (void)test1 {
  2. dispatch_queue_t queue = dispatch_queue_create("con", DISPATCH_QUEUE_CONCURRENT);
  3. NSLog(@"1");
  4. dispatch_async(queue, ^{
  5. NSLog(@"2");
  6. dispatch_sync(queue, ^{
  7. NSLog(@"3");
  8. });
  9. NSLog(@"4");
  10. });
  11. NSLog(@"5");
  12. }

截屏2020-12-27 上午10.39.40.png

截屏2020-12-27 上午10.40.37.png

异步+并发队列,performSelector底层,线程与runloop
截屏2020-12-27 上午10.44.48.png