AFNetworking+GCD处理并发问题

我们在编程的时候会经常会出现这样的需求:同时请求几个接口回调成功以后在统一刷新UI,解决这个问题的方法有很多今天我们就说明下GCD下解决的方式。

GCD的leave和enter 

我们利用 dispatch_group_t 创建队列组,手动管理group关联的block运行状态,进入和退出group的次数必须匹配。
//1.创建队列组
    dispatch_group_t group = dispatch_group_create();
    //2.创建队列
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    //3.添加请求
    dispatch_group_async(group, queue, ^{
        dispatch_group_enter(group);
        [HomeRequest getPointBuyAllConfigurationStrategyType:_dataType success:^(NSInteger code, NSDictionary *dict) {
            dispatch_group_leave(group);
        } failuer:^(NSInteger code, NSString *message) {
            dispatch_group_leave(group);
        }];
    });
    dispatch_group_async(group, queue, ^{
        dispatch_group_enter(group);
        [HomeRequest getStockLeverRiskStockCode:_buyingStrategyModel.stockCode strategyType:_dataType success:^(NSInteger code, NSDictionary *dict) {
            dispatch_group_leave(group);
        } failuer:^(NSInteger code, NSString *message) {
            dispatch_group_leave(group);
        }];
    });
    //4.队列组所有请求完成回调刷新UI
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        NSLog(@"model:%f",_buyingStrategyModel.leverrisk);
    });

GCD的信号量dispatch_semaphore_t

这种方式有点类似于通知模式,是利用监听信号量来发送消息以达到并发处理的效果,我们来看看代码:

//创建信号量
    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, ^{
        [HomeRequest getPointBuyAllConfigurationStrategyType:_dataType success:^(NSInteger code, NSDictionary *dict) {
            dispatch_semaphore_signal(semaphore);
        } failuer:^(NSInteger code, NSString *message) {
            dispatch_semaphore_signal(semaphore);
        }];
    });
    dispatch_group_async(group, queue, ^{
        [HomeRequest getStockLeverRiskStockCode:_buyingStrategyModel.stockCode strategyType:_dataType success:^(NSInteger code, NSDictionary *dict) {
            dispatch_semaphore_signal(semaphore);
        } failuer:^(NSInteger code, NSString *message) {
            dispatch_semaphore_signal(semaphore);
        }];
    });
    dispatch_group_notify(group, queue, ^{
        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
        NSLog(@"信号量为0");
    });

这两种方式都可以达到并发处理的效果,当然还有其他方式,大家一起学习吧!


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值