For XXFor XX

作为一个高手
我习惯了孤独

iOS GCD线程同步以及AFNetworking多次请求线程依赖

前言

针对于多线程同步以及依赖做一个小小的总结,以及当实际情况中比如在使用AFNetworking进行多次网络请求中如何进行线程依赖。

模拟数据

线程同步,最终执行完成操作(比如刷新UI)。
线程同步使用的是dispatch_group相关来实现。

测试代码:

//第一步创建队列
    dispatch_queue_t customQuue = dispatch_queue_create("com.manman.network", DISPATCH_QUEUE_CONCURRENT);
      //第二步创建组
    dispatch_group_t customGroup = dispatch_group_create();
    
    //第三步添加任务
    dispatch_group_async(customGroup, customQuue, ^{
        NSLog(@"吃饭");
    });
    
    dispatch_group_async(customGroup, customQuue, ^{
        NSLog(@"洗澡");
    });
    
    dispatch_group_async(customGroup, customQuue, ^{
        NSLog(@"睡觉");
    });
    dispatch_group_async(customGroup, customQuue, ^{
        NSLog(@"起床");
    });
    //第四步通知
    dispatch_group_notify(customGroup, dispatch_get_main_queue(), ^{
        NSLog(@"任务完成");
    });

打印结果:
QQ20180510-170344@2x.png

可以看到没什么问题,实现了线程同步,但是没有实现线程依赖。

如何实现线程依赖,依赖NSOperationQueue.

        NSBlockOperation *operation1 = [NSBlockOperation blockOperationWithBlock:^{
            NSLog(@"吃饭");
        }];
    
    
        NSBlockOperation *operation2 = [NSBlockOperation blockOperationWithBlock:^{
            NSLog(@"洗澡");
        }];
    
    
        NSBlockOperation *operation3 = [NSBlockOperation blockOperationWithBlock:^{
            NSLog(@"起床");
        }];
    
        NSBlockOperation *operation4 = [NSBlockOperation blockOperationWithBlock:^{
            NSLog(@"睡觉");
        }];
    
        NSBlockOperation *operation5 = [NSBlockOperation blockOperationWithBlock:^{
            NSLog(@"第二天");
        }];
        //4.设置依赖
        [operation2 addDependency:operation1];      //任务二依赖任务一
        [operation3 addDependency:operation2];      //任务三依赖任务二
    
        [operation4 addDependency:operation3];      //任务四依赖任务三

        [operation5 addDependency:operation4];
        //5.创建队列并加入任务
        NSOperationQueue *queue = [[NSOperationQueue alloc] init]; [queue addOperations:@[operation3, operation2, operation1,operation4,operation5] waitUntilFinished:NO];
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            NSLog(@"任务完成");
        }];

QQ20180510-175130@2x.png

可以看到是同步,并且依赖。

模拟数据实现了同步以及依赖,那么如果换做是真实的网络请求怎么样。

使用AFNetworking多次请求,实现线程同步以及依赖。

首先定义一个请求方法,(这里采用的是真实数据)

/**发起请求*/
-(void)requestWithType:(NSString *)type{
    
    AFHTTPSessionManager *manger =[AFHTTPSessionManager manager];
    
    manger.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    manger.requestSerializer = [AFHTTPRequestSerializer serializer];
    
    manger.requestSerializer.timeoutInterval = 30;
    
    manger.responseSerializer.acceptableContentTypes=[NSSet setWithObjects:@"application/json",@"text/json",@"text/javascript",@"text/html",nil,nil];
    
    NSString  *url = @"http://122.112.244.62/elevator/api/index.php/elevator/info?id=12345678711234567878";
    
    [manger GET:url parameters:nil progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSLog(@"%@",type);

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
    
        
}

同模拟数据,首先实现数据同步,只需要换个方法就行了吧。。

 //第一步创建队列
    dispatch_queue_t customQuue = dispatch_queue_create("com.manman.network", DISPATCH_QUEUE_CONCURRENT);
      //第二步创建组
    dispatch_group_t customGroup = dispatch_group_create();

    //第三步添加任务
    dispatch_group_async(customGroup, customQuue, ^{

        [self requestWithType:@"吃饭"];

    });

    dispatch_group_async(customGroup, customQuue, ^{


        [self requestWithType:@"洗澡"];


    });
    dispatch_group_async(customGroup, customQuue, ^{

        [self requestWithType:@"睡觉"];


    });
    dispatch_group_async(customGroup, customQuue, ^{

        [self requestWithType:@"起床"];

    });
    //第四步通知
    dispatch_group_notify(customGroup, dispatch_get_main_queue(), ^{
        NSLog(@"任务完成");
    });

看一下结果,8F4B6CFF-D8CD-4D7F-9D3F-A3FA5742BA14.png

是不是好奇怪,一样的方法只是换成AFNetworking,结果就不一样了,并没有实现线程同步,我们也都知道AFNetworking在进行网络请求的时候又开启了线程。
那么如何实现线程同步呢,借助信号量。

第一种方式:使用dispatch_semaphore_signal

dispatch_semaphore_create 创建一个semaphore
dispatch_semaphore_signal 发送一个信号
dispatch_semaphore_wait 等待信号

三个函数介绍:
第一个函数:创建一个整形数值的信号,即:信号的总量
第二个函数:发送一个信号,让信号总量增加1
第三个函数:首先判断信号量是否大于零,如果大于零则减掉1个信号量,往下执行,如果等于零则阻塞该线程

如何使用信号量来实现线程同步呢,
首先对请求方法做个改动

/**发起请求*/
-(void)requestWithType:(NSString *)type{
    
     dispatch_semaphore_t sema = dispatch_semaphore_create(0);
    AFHTTPSessionManager *manger =[AFHTTPSessionManager manager];
    
    manger.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    manger.requestSerializer = [AFHTTPRequestSerializer serializer];
    
    manger.requestSerializer.timeoutInterval = 30;
    
    manger.responseSerializer.acceptableContentTypes=[NSSet setWithObjects:@"application/json",@"text/json",@"text/javascript",@"text/html",nil,nil];
    
    NSString  *url = @"http://122.112.244.62/elevator/api/index.php/elevator/info?id=12345678711234567878";
    
    [manger GET:url parameters:nil progress:^(NSProgress * _Nonnull uploadProgress) {
        
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        //信号量+1
        long x  = dispatch_semaphore_signal(sema);
        NSLog(@"%@ --%ld",type,x);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //信号量+1
         dispatch_semaphore_signal(sema);
    }];
    //信号量-1
    long x =  dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
    NSLog(@"%@了 --%ld",type,x);
}

看一下结果:
2.png

可以看到实现了线程同步,任务完成在最后。

第二种

dispatch_group_enter:通知group,下面的任务马上要放到group中执行了。

dispatch_group_leave:通知group,任务完成了,该任务要从group中移除了。

//第一步创建队列
    dispatch_queue_t customQuue = dispatch_queue_create("com.manman.network", DISPATCH_QUEUE_CONCURRENT);
      //第二步创建组
    dispatch_group_t customGroup = dispatch_group_create();

    //第三步添加任务
    

    dispatch_group_async(customGroup, customQuue, ^{

        [self requestWithType:@"吃饭" group:customGroup];
;
    });

 

    dispatch_group_async(customGroup, customQuue, ^{
 
        [self requestWithType:@"洗澡" group:customGroup];
     


    });
  
    
    dispatch_group_async(customGroup, customQuue, ^{
     
        [self requestWithType:@"睡觉" group:customGroup];


    });
   
    dispatch_group_async(customGroup, customQuue, ^{
       

        [self requestWithType:@"起床" group:customGroup];
        

    });
    

    //第四步通知
    dispatch_group_notify(customGroup, dispatch_get_main_queue(), ^{
        NSLog(@"任务完成");
    });
    

请求方式修改:

/**发起请求*/
-(void)requestWithType:(NSString *)type group:(dispatch_group_t)group{
    
    
    dispatch_group_enter(group);
    AFHTTPSessionManager *manger =[AFHTTPSessionManager manager];
    
    manger.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    manger.requestSerializer = [AFHTTPRequestSerializer serializer];
    
    manger.requestSerializer.timeoutInterval = 30;
    
    manger.responseSerializer.acceptableContentTypes=[NSSet setWithObjects:@"application/json",@"text/json",@"text/javascript",@"text/html",nil,nil];
    
    NSString  *url = @"http://122.112.244.62/elevator/api/index.php/elevator/info?id=12345678711234567878";
    
    [manger GET:url parameters:nil progress:^(NSProgress * _Nonnull uploadProgress) {
        
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"%@",type);

        dispatch_group_leave(group);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

        dispatch_group_leave(group);
    }];

}

打印结果:3.png

可以看到实现了线程同步。但是并未依赖。

如何实现线程依赖。

NSOperation 结合信号量来实现。

  NSBlockOperation *operation1 = [NSBlockOperation blockOperationWithBlock:^{
           [self requestWithType:@"吃饭"];
        }];


        NSBlockOperation *operation2 = [NSBlockOperation blockOperationWithBlock:^{
            [self requestWithType:@"洗澡"];

        }];


        NSBlockOperation *operation3 = [NSBlockOperation blockOperationWithBlock:^{
            [self requestWithType:@"起床"];

        }];

        NSBlockOperation *operation4 = [NSBlockOperation blockOperationWithBlock:^{
            [self requestWithType:@"睡觉"];

        }];

        NSBlockOperation *operation5 = [NSBlockOperation blockOperationWithBlock:^{
            [self requestWithType:@"第二天"];

        }];
    
    NSBlockOperation *operation6 = [NSBlockOperation blockOperationWithBlock:^{
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            NSLog(@"任务完成,刷新UI");
        }];
        
    }];
        //4.设置依赖
        [operation2 addDependency:operation1];      //任务二依赖任务一
        [operation3 addDependency:operation2];      //任务三依赖任务二

        [operation4 addDependency:operation3];      //任务四依赖任务三

        [operation5 addDependency:operation4];
        [operation6 addDependency:operation5];

    
        //5.创建队列并加入任务
        NSOperationQueue *queue = [[NSOperationQueue alloc] init]; [queue addOperations:@[operation3, operation2, operation1,operation4,operation5,operation6] waitUntilFinished:NO];

    
    
}

/**发起请求*/
-(void)requestWithType:(NSString *)type{
    
    
    dispatch_semaphore_t sema = dispatch_semaphore_create(0);
    AFHTTPSessionManager *manger =[AFHTTPSessionManager manager];
    
    manger.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    manger.requestSerializer = [AFHTTPRequestSerializer serializer];
    
    manger.requestSerializer.timeoutInterval = 30;
    
    manger.responseSerializer.acceptableContentTypes=[NSSet setWithObjects:@"application/json",@"text/json",@"text/javascript",@"text/html",nil,nil];
    
    NSString  *url = @"http://122.112.244.62/elevator/api/index.php/elevator/info?id=12345678711234567878";
    
    [manger GET:url parameters:nil progress:^(NSProgress * _Nonnull uploadProgress) {
        
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"%@",type);

        dispatch_semaphore_signal(sema);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
     dispatch_semaphore_signal(sema);
        
    }];
    dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
}

打印结果:

3A128FD1-944F-4CD2-BA3A-D9EA5BA72295.png

转载请注明出处:For XX » iOS GCD线程同步以及AFNetworking多次请求线程依赖
标签:iOS
分享到: 更多