Block 异步转同步

使用信号量同步异步任务

在程序开发中,有时候我们不想使用异步方式,例如我们想要调用函数后立刻获取结果值的时候,然后进行后续的数据操作。 这个时候需要信号量来等待返回结果,然后等到结果返回,从而进行后续处理。

//创建一个全局队列 
        dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
        dispatch_async(queue, ^{
            for (int i=0; i<=2; i++) {
                NSDictionary *testDict = @{@"service":self.clientToken,@"config":self.config};
                [TestAPI invocationInterface:i param:testDict];
            }
        });
//创建一个信号量(值为0)
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
        [[LYCloudService sharedLYCloudService] startCloudService:dict[@"service"] config:dict[@"config"] startBlock:^(LYstatusCode statusCode, NSString *errorString) {
            NSString * tips = [NSString stringWithFormat:@"启动云服务: LYstatusCode: %ld, errorString: %@", (long)statusCode, errorString];
            WLog(@"%@",tips);
            //信号量加1
            dispatch_semaphore_signal(semaphore);
        } popMessageBlock:^(NSDictionary *dictionary) {
            WLog(@"%@",dictionary);
        }];
        
        //信号量减1,如果>0,则向下执行,否则等待
        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);

转载于:https://my.oschina.net/u/1763048/blog/742512

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值