并发进程执行的同步

时间:2012-10-15 14:25:26

标签: ios multithreading

我有一些数据处理的并发操作。在处理过程中,我需要检索该位置的反向地理编码。众所周知,- (void)reverseGeocodeLocation:(CLLocation *)location completionHandler:(CLGeocodeCompletionHandler)completionHandler也在后台线程中执行地理编码请求,并在调用后立即返回。当地理编码完成请求时,它会在主线程上执行完成处理程序。在地理编码器检索结果之前,如何阻止并发操作?

__block CLPlacemark *_placemark

- (NSDictionary *)performDataProcessingInCustomThread
{
    NSMutableDictionary *dict = [NSMutableDictionary alloc] initWithCapacity:1];
    // some operations

    CLLocation *location = [[CLLocation alloc] initWithLatitude:40.7 longitude:-74.0];
    [self proceedReverseGeocoding:location];

    // wait until the geocoder request completes

    if (_placemark) {
        [dict setValue:_placemark.addressDictionary forKey:@"AddressDictionary"];

    return dict;
}

- (void)proceedReverseGeocoding:(CLLocation *)location
{
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
        if ([error code] == noErr) {
            _placemark = placemarks.lastObject;
        }
    }];
}

1 个答案:

答案 0 :(得分:2)

为实现这一目标,我们可以使用dispatch_semaphore_t。首先,我们需要在类中添加信号量:

dispatch_semaphore_t semaphore;

当我们处理数据并准备接收地理编码数据时,我们应该创建调度信号量并开始等待信号:

semaphore = dispatch_semaphore_create(0);
[self proceedReverseGeocoding:location];
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);

在CLGeocodeCompletionHandler的末尾,我们需要的是发送信号以恢复数据处理:

dispatch_semaphore_signal(semaphore);

此后数据处理将继续

相关问题