并发进程执行的同步

编程入门 行业动态 更新时间:2024-10-26 12:24:34
本文介绍了并发进程执行的同步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一些用于数据处理的并发操作.在处理过程中,我需要检索该位置的反向地理编码.据了解,- (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);

此后数据处理将继续

更多推荐

并发进程执行的同步

本文发布于:2023-10-28 00:44:26,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1535002.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:进程

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!