iOS底层

dispatch_semaphore_t、dispatch_gr

2020-07-06  本文已影响0人  Jean_Lina
#pragma dispatch_semaphore_t、dispatch_group_t实现线程同步
- (void)dispatch_semaphore_group {
  //创建信号量
  dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
  // 创建全局并行
  dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
  dispatch_group_t group = dispatch_group_create();
  dispatch_group_async(group, queue, ^{
      // 请求一
      [NSThread sleepForTimeInterval:3];
      NSLog(@"网络请求一 %@", [NSThread currentThread]);
      dispatch_semaphore_signal(semaphore);
  });
  dispatch_group_async(group, queue, ^{
      // 请求二
      [NSThread sleepForTimeInterval:5];
      NSLog(@"网络请求二 %@", [NSThread currentThread]);
      dispatch_semaphore_signal(semaphore);
  });
  dispatch_group_async(group, queue, ^{
      // 请求三
      [NSThread sleepForTimeInterval:4];
      NSLog(@"网络请求三 %@", [NSThread currentThread]);
      dispatch_semaphore_signal(semaphore);
  });
  dispatch_group_notify(group, queue, ^{
      //三个请求对应三次信号等待
      NSLog(@"等待前 %@", [NSThread currentThread]);
      dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
      dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
      dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
      NSLog(@"等待结束 %@", [NSThread currentThread]);
      //在这里 进行请求后的方法,回到主线程
      dispatch_async(dispatch_get_main_queue(), ^{
          //更新UI操作
          NSLog(@"回到主线程,刷新UI %@", [NSThread currentThread]);
      });
  });
}
输出结果:
2020-07-06 17:25:17.726348+0800 GCD[3677:1220884] 网络请求一 <NSThread: 0x2807c9b00>{number = 7, name = (null)}
2020-07-06 17:25:18.724849+0800 GCD[3677:1220887] 网络请求三 <NSThread: 0x2807c60c0>{number = 8, name = (null)}
2020-07-06 17:25:19.726204+0800 GCD[3677:1220883] 网络请求二 <NSThread: 0x2807c5f00>{number = 9, name = (null)}
2020-07-06 17:25:19.726402+0800 GCD[3677:1220887] 等待前 <NSThread: 0x2807c60c0>{number = 8, name = (null)}
2020-07-06 17:25:19.726488+0800 GCD[3677:1220887] 等待结束 <NSThread: 0x2807c60c0>{number = 8, name = (null)}
2020-07-06 17:25:19.726636+0800 GCD[3677:1220848] 回到主线程,刷新UI <NSThread: 0x280798d80>{number = 1, name = main}
上一篇 下一篇

猜你喜欢

热点阅读