return方法中需要用到同步请求数据的结果,但是网络请求返回block中又不能直接写return,因此想到用信号量来解决,实践一番,用信号量居然导致线程卡死了。追溯下卡死的原因:是因为AFN返回结果的blcok中,若没有设置其他线程,则默认主线程执行block内容,而此时的信号量等待把主线程给卡死了,主线程执行不下去,就gg了。
AFN源码:
AFN源码.png解决办法:
- (NSString *)getDataA {
__block NSString *dataTest = @"getDataA____信号量同步数据GG了!!!";
//创建信号量
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
//记得信号量同步时给manager.completionQueue设置个队列,否则AFN默认block在主线程执行,此时设置信号量导致卡死
manager.completionQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
NSURL *URL = [NSURL URLWithString:@"http://rap2api.taobao.org/app/mock/256798/api/chat/list"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request uploadProgress:nil downloadProgress:nil completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (error) {
NSLog(@"Error: %@", error);
} else {
NSLog(@"%@ %@", response, responseObject);
}
NSLog(@"DISPATCH_QUEUE_CONCURRENT___故障现象数据请求下来了哦,可以进行下一步了");
dataTest = @"getDataA____信号量同步数据已经请求下来了!!!";
dispatch_semaphore_signal(semaphore);
}];
[dataTask resume];
//信号量等待
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
NSLog(@"DISPATCH_QUEUE_CONCURRENT___进一步操作数据");
return dataTest;
}
在此记录一下,看到的希望能帮到你。本篇GitHubDemo传送阵在此。
网友评论