在程序开发中,有时候我们不想使用异步方式,例如我们想要调用函数后立刻获取结果值的时候,然后进行后续的数据操作。 这个时候需要信号量来等待返回结果,然后等到结果返回,从而进行后续处理。
//创建一个全局队列
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);