DispatchGroup

一、DispatchGroup三种用法:

1.notify(依赖任务)
  func testNotify() {
        let group = DispatchGroup()
        let myQueue = DispatchQueue(label: "com.aa")
        myQueue.async(group: group, qos: .default, flags: []) {
            for _ in 0...10 {
                print("耗时任务一")
            }
        }
        myQueue.async(group: group, qos: .default, flags: []){
                   for _ in 0...10 {
                       print("耗时任务二")
                   }
        }
        
        //执行完上面的两个耗时操作, 回到myQueue队列中执行下一步的任务
           group.notify(queue: myQueue) {
               print("回到该队列中执行")
           }
        
    }

打印结果

耗时任务一
耗时任务一
耗时任务一
耗时任务一
耗时任务一
耗时任务一
耗时任务一
耗时任务一
耗时任务一
耗时任务一
耗时任务一
耗时任务二
耗时任务二
耗时任务二
耗时任务二
耗时任务二
耗时任务二
耗时任务二
耗时任务二
耗时任务二
耗时任务二
耗时任务二
回到该队列中执行
2.wait(任务等待)
  func testNotify() {
        let group = DispatchGroup()
        let myQueue = DispatchQueue(label: "com.aa")
        myQueue.async(group: group, qos: .default, flags: []) {
            for _ in 0...10 {
                print("耗时任务一")
            }
        }
        myQueue.async(group: group, qos: .default, flags: []){
                   for _ in 0...10 {
                       print("耗时任务二")
                   }
        }
        
        //执行完上面的两个耗时操作, 回到myQueue队列中执行下一步的任务
        group.wait(timeout: DispatchTime.distantFuture)
        print("接下来的操作")
        
    }

打印结果

耗时任务一
耗时任务一
耗时任务一
耗时任务一
耗时任务一
耗时任务一
耗时任务一
耗时任务一
耗时任务一
耗时任务一
耗时任务一
耗时任务二
耗时任务二
耗时任务二
耗时任务二
耗时任务二
耗时任务二
耗时任务二
耗时任务二
耗时任务二
耗时任务二
耗时任务二
接下来的操作

3.enter leave 手动管理group计数,enter和leave必须配对

    func testNotify() {
        let group = DispatchGroup()
        let myQueue = DispatchQueue(label: "com.aa")
         group.enter()//把该任务添加到组队列中执行
      myQueue.async(group: group, qos: .default, flags: [], execute: {
          for _ in 0...10 {
              print("耗时任务一")
              
          }
        group.leave()//执行完之后从组队列中移除
      })
        group.enter()//把该任务添加到组队列中执行
      myQueue.async(group: group, qos: .default, flags: [], execute: {
               for _ in 0...10 {
                   print("耗时任务二")
                   
               }
            group.leave()//执行完之后从组队列中移除
     })
        
        //执行完上面的两个耗时操作, 回到myQueue队列中执行下一步的任务
        //当上面所有的任务执行完之后通知
       
        print("接下来的操作开始")
       group.notify(queue: .main) {
           print("所有的任务执行完了")
       }
        print("接下来的操作结束")
        
    }

打印结果

接下来的操作开始
接下来的操作结束
耗时任务一
耗时任务一
耗时任务一
耗时任务一
耗时任务一
耗时任务一
耗时任务一
耗时任务一
耗时任务一
耗时任务一
耗时任务一
耗时任务二
耗时任务二
耗时任务二
耗时任务二
耗时任务二
耗时任务二
耗时任务二
耗时任务二
耗时任务二
耗时任务二
耗时任务二
所有的任务执行完了
Notify与wait的区别
   func testNotify2() {
        print("开始设置任务")
        DispatchQueue.main.async {
            let group  = DispatchGroup()
            let taskQueue = DispatchQueue(label: "ccc")
            for i in 0..<3 {
                group.enter()
                taskQueue.async {
                    print("开始第\(i)项任务")
                    sleep(UInt32(1))
                    print("结束第\(i)项任务")
                    group.leave()
                }
            }
            
            group.notify(queue: taskQueue) {
                print("全部执行完毕")
            }
          
        }
        
    }
   func testNotify2() {
        print("开始设置任务")
        DispatchQueue.main.async {
            let group  = DispatchGroup()
            let taskQueue = DispatchQueue(label: "ccc")
            for i in 0..<3 {
                group.enter()
                taskQueue.async {
                    print("开始第\(i)项任务")
                    sleep(UInt32(1))
                    print("结束第\(i)项任务")
                    group.leave()
                }
            }
            
            let result = group.wait(timeout: DispatchTime(uptimeNanoseconds: 1))
            if result == .success {
                print("全部任务完成")
            }else{
                print("任务超时")
            }
          
        }
        print("结束了么")
        
    }

打印结果

开始设置任务
结束了么
容器
任务超时
开始第0项任务
结束第0项任务
开始第1项任务
结束第1项任务
开始第2项任务
结束第2项任务
 func testNotify2() {
        print("开始设置任务")
        DispatchQueue.main.async {
            let group  = DispatchGroup()
            let taskQueue = DispatchQueue(label: "ccc")
            for i in 0..<3 {
                group.enter()
                taskQueue.async {
                    print("开始第\(i)项任务")
                    sleep(UInt32(1))
                    print("结束第\(i)项任务")
                    group.leave()
                }
            }
            
            let result = group.wait(timeout: DispatchTime.distantFuture)
            if result == .success {
                print("全部任务完成")
            }else{
                print("任务超时")
            }
          
        }
        print("结束了么")
        
    }
    

打印结果

开始设置任务
结束了么
容器
开始第0项任务
结束第0项任务
开始第1项任务
结束第1项任务
开始第2项任务
结束第2项任务
全部任务完成

下载真实图片,串联执行

Swift

  dispatch_queue_t myQuue = dispatch_queue_create("aa", DISPATCH_QUEUE_SERIAL);
    dispatch_async(myQuue, ^{
         NSLog(@"开始第 1 个任务。%@", [NSThread currentThread]);
          NSURL *url = [NSURL URLWithString:@"http://www.xinhuanet.com/photo/2018-03/13/1122528717_15209051820841n.jpg"];
        NSData *data = [NSData dataWithContentsOfURL:url];
         UIImage *image = [UIImage imageWithData:data];
        
               NSLog(@"结束第 1 个任务。%@", image);
    });
    
    dispatch_async(myQuue, ^{
          NSLog(@"开始第 2 个任务。%@", [NSThread currentThread]);
                     NSURL *url = [NSURL URLWithString:@"http://www.xinhuanet.com/photo/2018-03/13/1122528717_15209051820841n.jpg"];
                NSData *data = [NSData dataWithContentsOfURL:url];
                 UIImage *image = [UIImage imageWithData:data];
                NSLog(@"结束第 2 个任务。%@",image);
    });
    
    dispatch_async(myQuue, ^{
             NSLog(@"开始第 3 个任务。%@", [NSThread currentThread]);
                            NSURL *url = [NSURL URLWithString:@"http://www.xinhuanet.com/photo/2018-03/13/1122528717_15209051820841n.jpg"];
                   NSData *data = [NSData dataWithContentsOfURL:url];
                    UIImage *image = [UIImage imageWithData:data];
                   NSLog(@"结束第 3 个任务。%@",image);
       });
2020-06-02 16:00:01.892165+0800 OCTestFirst[9165:258513] 开始第 1 个任务。<NSThread: 0x600000c11100>{number = 3, name = (null)}
2020-06-02 16:00:05.537238+0800 OCTestFirst[9165:258513] 结束第 1 个任务。<UIImage:0x600002b44d80 anonymous {900, 687}>
2020-06-02 16:00:05.537566+0800 OCTestFirst[9165:258513] 开始第 2 个任务。<NSThread: 0x600000c11100>{number = 3, name = (null)}
2020-06-02 16:00:05.971256+0800 OCTestFirst[9165:258513] 结束第 2 个任务。<UIImage:0x600002b54870 anonymous {900, 687}>
2020-06-02 16:00:05.971575+0800 OCTestFirst[9165:258513] 开始第 3 个任务。<NSThread: 0x600000c11100>{number = 3, name = (null)}
2020-06-02 16:00:05.989165+0800 OCTestFirst[9165:258513] 结束第 3 个任务。<UIImage:0x600002b47960 anonymous {900, 687}>

OC的dispatch_group_enter,dispatch_group_leave和notify的应用

   dispatch_queue_t myQuue = dispatch_queue_create("aa", DISPATCH_QUEUE_CONCURRENT);
    dispatch_group_t myGroup = dispatch_group_create();
    
    dispatch_group_async(myGroup, myQuue, ^{
         dispatch_group_enter(myGroup);
                NSLog(@"开始第 1 个任务。%@", [NSThread currentThread]);
                 NSURL *url = [NSURL URLWithString:@"http://www.xinhuanet.com/photo/2018-03/13/1122528717_15209051820841n.jpg"];
               NSData *data = [NSData dataWithContentsOfURL:url];
                UIImage *image = [UIImage imageWithData:data];
               
                      NSLog(@"结束第 1 个任务。%@", image);
        dispatch_group_leave(myGroup);
    });
    
  
    dispatch_group_async(myGroup, myQuue, ^{
         dispatch_group_enter(myGroup);
                 NSLog(@"开始第 2 个任务。%@", [NSThread currentThread]);
                            NSURL *url = [NSURL URLWithString:@"http://www.xinhuanet.com/photo/2018-03/13/1122528717_15209051820841n.jpg"];
                       NSData *data = [NSData dataWithContentsOfURL:url];
                        UIImage *image = [UIImage imageWithData:data];
                       NSLog(@"结束第 2 个任务。%@",image);
                dispatch_group_leave(myGroup);
    });
    
    dispatch_group_async(myGroup, myQuue, ^{
        dispatch_group_enter(myGroup);
            NSLog(@"开始第 3 个任务。%@", [NSThread currentThread]);
                           NSURL *url = [NSURL URLWithString:@"http://www.xinhuanet.com/photo/2018-03/13/1122528717_15209051820841n.jpg"];
                  NSData *data = [NSData dataWithContentsOfURL:url];
                   UIImage *image = [UIImage imageWithData:data];
                  NSLog(@"结束第 3 个任务。%@",image);
        dispatch_group_leave(myGroup);
    });
  
    

    dispatch_group_notify(myGroup, myQuue, ^{
        NSLog(@"将要执行");
    });

打印结果

2020-06-02 16:16:41.128073+0800 OCTestFirst[9467:270577] 开始第 1 个任务。<NSThread: 0x600003928080>{number = 2, name = (null)}
2020-06-02 16:16:41.128031+0800 OCTestFirst[9467:270574] 开始第 2 个任务。<NSThread: 0x600003939fc0>{number = 3, name = (null)}
2020-06-02 16:16:41.128144+0800 OCTestFirst[9467:270578] 开始第 3 个任务。<NSThread: 0x60000393a180>{number = 4, name = (null)}
2020-06-02 16:16:43.365683+0800 OCTestFirst[9467:270574] 结束第 2 个任务。<UIImage:0x600001e71050 anonymous {900, 687}>
2020-06-02 16:16:43.365691+0800 OCTestFirst[9467:270577] 结束第 1 个任务。<UIImage:0x600001e72370 anonymous {900, 687}>
2020-06-02 16:16:43.365707+0800 OCTestFirst[9467:270578] 结束第 3 个任务。<UIImage:0x600001e7db00 anonymous {900, 687}>
2020-06-02 16:16:43.366060+0800 OCTestFirst[9467:270577] 将要执行
dispatch_barrier_Async
       
 
    dispatch_queue_t myQuue = dispatch_queue_create("mmm", DISPATCH_QUEUE_CONCURRENT);
    
    dispatch_async(myQuue, ^{
        NSLog(@"开始第 1 个任务。%@", [NSThread currentThread]);
                     NSURL *url = [NSURL URLWithString:@"http://www.xinhuanet.com/photo/2018-03/13/1122528717_15209051820841n.jpg"];
                   NSData *data = [NSData dataWithContentsOfURL:url];
                    UIImage *image = [UIImage imageWithData:data];
        NSLog(@"结束第 1 个任务。%@", [NSThread currentThread]);
    });
    
    dispatch_async(myQuue, ^{
         NSLog(@"开始第 2 个任务。%@", [NSThread currentThread]);
                        NSURL *url = [NSURL URLWithString:@"http://www.xinhuanet.com/photo/2018-03/13/1122528717_15209051820841n.jpg"];
                      NSData *data = [NSData dataWithContentsOfURL:url];
                       UIImage *image = [UIImage imageWithData:data];
           NSLog(@"结束第 2 个任务。%@", [NSThread currentThread]);
       });
  
    dispatch_barrier_async(myQuue, ^{
        NSLog(@"中间执行的过程");
    });
    dispatch_async(myQuue, ^{
            NSLog(@"开始第 3 个任务。%@", [NSThread currentThread]);
                         NSURL *url = [NSURL URLWithString:@"http://www.xinhuanet.com/photo/2018-03/13/1122528717_15209051820841n.jpg"];
                       NSData *data = [NSData dataWithContentsOfURL:url];
                        UIImage *image = [UIImage imageWithData:data];
            NSLog(@"结束第 3 个任务。%@", [NSThread currentThread]);
          });

打印结果

2020-06-02 16:32:41.380768+0800 OCTestFirst[9742:282073] 开始第 1 个任务。<NSThread: 0x6000030842c0>{number = 2, name = (null)}
2020-06-02 16:32:41.381077+0800 OCTestFirst[9742:282077] 开始第 2 个任务。<NSThread: 0x600003095100>{number = 4, name = (null)}
2020-06-02 16:32:44.191922+0800 OCTestFirst[9742:282077] 结束第 2 个任务。<NSThread: 0x600003095100>{number = 4, name = (null)}
2020-06-02 16:32:44.212357+0800 OCTestFirst[9742:282073] 结束第 1 个任务。<NSThread: 0x6000030842c0>{number = 2, name = (null)}
2020-06-02 16:32:44.213365+0800 OCTestFirst[9742:282073] 中间执行的过程
2020-06-02 16:32:44.213740+0800 OCTestFirst[9742:282073] 开始第 3 个任务。<NSThread: 0x6000030842c0>{number = 2, name = (null)}
2020-06-02 16:32:44.782746+0800 OCTestFirst[9742:282073] 结束第 3 个任务。<NSThread: 0x6000030842c0>{number = 2, name = (null)}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Swift DispatchGroup is a class in the Swift programming language that allows you to synchronize the execution of multiple tasks running on different threads. It helps you to manage the timing of asynchronous operations and avoid race conditions. A DispatchGroup is a lightweight mechanism for tracking a group of tasks. You can add tasks to a group, and the group will notify you when all of the tasks have completed. You can also specify a timeout for the group, after which the group will notify you if any of the tasks have not completed. Here is an example of how to use a DispatchGroup: ``` let group = DispatchGroup() group.enter() // run task 1 group.leave() group.enter() // run task 2 group.leave() group.notify(queue: .main) { // both tasks have completed } ``` In this example, we create a DispatchGroup called `group`. We then use the `enter()` and `leave()` methods to add two tasks to the group. The `notify()` method is called when both tasks have completed, and we can then perform any necessary actions. You can also use a DispatchGroup to wait for a group of tasks to complete before continuing execution. Here's an example: ``` let group = DispatchGroup() group.enter() // run task 1 group.leave() group.enter() // run task 2 group.leave() group.wait() // both tasks have completed ``` In this example, we use the `wait()` method to wait for both tasks to complete before continuing execution. This can be useful if you need to ensure that all tasks have completed before performing additional actions.

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值