iOS-GCD使用详解及实例解析

2020-01-18 17:17:18王旭

步骤图

iOS-GCD使用详解,iOS-GCD使用详解解析,iOS-GCD使用详解实例代码

(三)同步执行 + 并行队列

实现代码:


//同步执行 + 并行队列
- (void)syncConcurrent{
  //创建一个并行队列
  dispatch_queue_t queue = dispatch_queue_create("标识符", DISPATCH_QUEUE_CONCURRENT);
 
  NSLog(@"---start---");
  //使用同步函数封装三个任务
  dispatch_sync(queue, ^{
    NSLog(@"任务1---%@", [NSThread currentThread]);
  });
  dispatch_sync(queue, ^{
    NSLog(@"任务2---%@", [NSThread currentThread]);
  });
  dispatch_sync(queue, ^{
    NSLog(@"任务3---%@", [NSThread currentThread]);
  });
  NSLog(@"---end---");
}

 打印结果:

1 2 3 4 5 ---start---   任务1---{number = 1, name = main}   任务2---{number = 1, name = main}   任务3---{number = 1, name = main}   ---end---

解释

    同步执行执行意味着

      不能开启新的线程

      任务创建后必须执行完才能往下走

      并行队列意味着

        任务必须按添加进队列的顺序挨个执行

        两者组合后的结果

          所有任务都只能在主线程中执行

          函数在执行时,必须按照代码的书写顺序一行一行地执行完才能继续

          注意事项

            在这里即便是并行队列,任务可以同时执行,但是由于只存在一个主线程,所以没法把任务分发到不同的线程去同步处理,其结果就是只能在主线程里按顺序挨个挨个执行了

            步骤图

            iOS-GCD使用详解,iOS-GCD使用详解解析,iOS-GCD使用详解实例代码

            (四)同步执行+ 串行队列

            实现代码:

            
            - (void)syncSerial{
              //创建一个串行队列
              dispatch_queue_t queue = dispatch_queue_create("标识符", DISPATCH_QUEUE_SERIAL);
             
              NSLog(@"---start---");
              //使用异步函数封装三个任务
              dispatch_sync(queue, ^{
                NSLog(@"任务1---%@", [NSThread currentThread]);
              });
              dispatch_sync(queue, ^{
                NSLog(@"任务2---%@", [NSThread currentThread]);
              });
              dispatch_sync(queue, ^{
                NSLog(@"任务3---%@", [NSThread currentThread]);
              });
              NSLog(@"---end---");
            }