并发进程执行的同步 [英] Synchronization of concurrent processes execution

查看:95
本文介绍了并发进程执行的同步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have some concurrent operation for the data processing. During the processing I need to retrieve the reverse geocoding for the location. It is known that - (void)reverseGeocodeLocation:(CLLocation *)location completionHandler:(CLGeocodeCompletionHandler)completionHandler also performs geocoding request in background thread and returns immediately after the call. When geocoded finishes request it executes the completion handler on the main thread. How can I block my concurrent operation until the geocoder retrieves the result?

__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;
        }
    }];
}

推荐答案

为了实现这一点,我们可以使用 dispatch_semaphore_t.首先我们需要给类添加信号量:

To achieve this we can use dispatch_semaphore_t. First of all we need to add semaphore to the class:

dispatch_semaphore_t semaphore;

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

When we are processing data and ready to receive the geocoding data, we should create dispatch semaphore and start to wait a signal:

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

在 CLGeocodeCompletionHandler 结束时,我们只需要发送信号以恢复数据处理:

At the end of CLGeocodeCompletionHandler all we need is to send the signal to resume the data processing:

dispatch_semaphore_signal(semaphore);

此后数据处理将继续

这篇关于并发进程执行的同步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆