1.

dispatch_group_enter(group);

dispatch_group_leave(group);

dispatch_group_notify(group1, queue1,block);

在这种组合下,根据任务是同步、异步又分为两种,这两种组合的执行代码与运行结果如下:

第一种:同步任务时

 dispatch_queue_t queue2 = dispatch_queue_create("dispatchGroupMethod2.queue2", DISPATCH_QUEUE_CONCURRENT);
dispatch_group_t group2 = dispatch_group_create(); dispatch_group_enter(group2);
dispatch_sync(queue2, ^{
for (NSInteger i =0; i<3; i++) {
sleep(1);
NSLog(@"%@-同步任务执行-:%ld",@"任务1",(long)i); }
dispatch_group_leave(group2);
}); dispatch_group_enter(group2);
dispatch_sync(queue2, ^{
for (NSInteger i =0; i<3; i++) {
sleep(1);
NSLog(@"%@-同步任务执行-:%ld",@"任务2",(long)i); }
dispatch_group_leave(group2);
}); // //等待上面的任务全部完成后,会往下继续执行 (会阻塞当前线程)
// dispatch_group_wait(group2, DISPATCH_TIME_FOREVER); //等待上面的任务全部完成后,会收到通知执行block中的代码 (不会阻塞线程)
dispatch_group_notify(group2, queue2, ^{
NSLog(@"Method2-全部任务执行完成");
});

同步任务执行结果:

第二种:异步任务时

   dispatch_queue_t queue2 = dispatch_queue_create("dispatchGroupMethod2.queue2", DISPATCH_QUEUE_CONCURRENT);
dispatch_group_t group2 = dispatch_group_create(); dispatch_group_enter(group2);
dispatch_async(queue2, ^{
for (NSInteger i =0; i<3; i++) {
sleep(1);
NSLog(@"%@-异步任务执行-:%ld",@"任务1",(long)i); }
dispatch_group_leave(group2);
}); dispatch_group_enter(group2);
dispatch_async(queue2, ^{
for (NSInteger i =0; i<3; i++) {
sleep(1);
NSLog(@"%@-异步任务执行-:%ld",@"任务2",(long)i); }
dispatch_group_leave(group2);
}); // //等待上面的任务全部完成后,会往下继续执行 (会阻塞当前线程)
// dispatch_group_wait(group2, DISPATCH_TIME_FOREVER); //等待上面的任务全部完成后,会收到通知执行block中的代码 (不会阻塞线程)
dispatch_group_notify(group2, queue2, ^{
NSLog(@"Method2-全部任务执行完成");
});

异步任务执行结果:

https://www.cnblogs.com/zhou--fei/p/6747938.html

2.

创建一个信号量,作为全局变量。
并初始化,信号量为0

dispatch_semaphore_t semaphore;
semaphore = dispatch_semaphore_create(0);

创建一个dispatch_group_t,开启两个组异步线程(dispatch_group_async),分别执行两个网络请求。
一个组通知线程(dispatch_group_notify),用于接收前面两个线程的结果。

dispatch_group_t group = dispatch_group_create();
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_group_async(group, queue, ^{
[weakSelf loadRelationDetail];//请求1
});
dispatch_group_async(group, queue, ^{
[weakSelf loadRelationReward];//请求2
});
dispatch_group_notify(group, queue, ^{
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
//合并(此处是数据处理,你可根据具体业务需求进行处理)
NSMutableArray *arr = [NSMutableArray array];
[arr addObjectsFromArray:weakSelf.arr1];
[arr addObjectsFromArray:weakSelf.arr2];
//排序
if (arr.count > 1) {
weakSelf.sumArr = [arr sortedArrayUsingComparator:^NSComparisonResult(ZHShareItem *obj1, ZHShareItem *obj2) {
return [obj1.createTime compare:obj2.createTime];
}];
}else{
weakSelf.sumArr = arr;
}
//有数据刷新
if (weakSelf.sumArr.count > 0) {
//在主线程刷新页面
dispatch_async(dispatch_get_main_queue(), ^{
[weakSelf initTableView];
});
}
});

https://www.jianshu.com/p/4e997f5deda9

3.afnetworking

为每一个NSURLSessionDownloadTask创建AFURLSessionManagerTaskDelegate,把请求的completionHandler也放在delegate。

从统一的回调didCompleteWithError到delegate的didCompleteWithError,再调用completionHandler返回。

- (void)addDelegateForDownloadTask:(NSURLSessionDownloadTask *)downloadTask
progress:(void (^)(NSProgress *downloadProgress)) downloadProgressBlock
destination:(NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination
completionHandler:(void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler
{
AFURLSessionManagerTaskDelegate *delegate = [[AFURLSessionManagerTaskDelegate alloc] init];
delegate.manager = self;
delegate.completionHandler = completionHandler; if (destination) {
delegate.downloadTaskDidFinishDownloading = ^NSURL * (NSURLSession * __unused session, NSURLSessionDownloadTask *task, NSURL *location) {
return destination(location, task.response);
};
} downloadTask.taskDescription = self.taskDescriptionForSessionTasks; [self setDelegate:delegate forTask:downloadTask]; delegate.downloadProgressBlock = downloadProgressBlock;
}

response

- (void)URLSession:(NSURLSession *)session
task:(NSURLSessionTask *)task
didCompleteWithError:(NSError *)error
{
AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:task]; // delegate may be nil when completing a task in the background
if (delegate) {
[delegate URLSession:session task:task didCompleteWithError:error];
...
//需要加锁
- (AFURLSessionManagerTaskDelegate *)delegateForTask:(NSURLSessionTask *)task {
NSParameterAssert(task); AFURLSessionManagerTaskDelegate *delegate = nil;
[self.lock lock];
delegate = self.mutableTaskDelegatesKeyedByTaskIdentifier[@(task.taskIdentifier)];
[self.lock unlock]; return delegate;
} ...
//每一个delegate #pragma mark - NSURLSessionTaskDelegate - (void)URLSession:(__unused NSURLSession *)session
task:(NSURLSessionTask *)task
didCompleteWithError:(NSError *)error
{
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wgnu"
__strong AFURLSessionManager *manager = self.manager; __block id responseObject = nil; __block NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
userInfo[AFNetworkingTaskDidCompleteResponseSerializerKey] = manager.responseSerializer; //Performance Improvement from #2672
NSData *data = nil;
if (self.mutableData) {
data = [self.mutableData copy];
//We no longer need the reference, so nil it out to gain back some memory.
self.mutableData = nil;
} if (self.downloadFileURL) {
userInfo[AFNetworkingTaskDidCompleteAssetPathKey] = self.downloadFileURL;
} else if (data) {
userInfo[AFNetworkingTaskDidCompleteResponseDataKey] = data;
} if (error) {
userInfo[AFNetworkingTaskDidCompleteErrorKey] = error; dispatch_group_async(manager.completionGroup ?: url_session_manager_completion_group(), manager.completionQueue ?: dispatch_get_main_queue(), ^{
if (self.completionHandler) {
self.completionHandler(task.response, responseObject, error);
} dispatch_async(dispatch_get_main_queue(), ^{
[[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingTaskDidCompleteNotification object:task userInfo:userInfo];
});
});
} else {
dispatch_async(url_session_manager_processing_queue(), ^{
NSError *serializationError = nil;
responseObject = [manager.responseSerializer responseObjectForResponse:task.response data:data error:&serializationError]; if (self.downloadFileURL) {
responseObject = self.downloadFileURL;
} if (responseObject) {
userInfo[AFNetworkingTaskDidCompleteSerializedResponseKey] = responseObject;
} if (serializationError) {
userInfo[AFNetworkingTaskDidCompleteErrorKey] = serializationError;
} dispatch_group_async(manager.completionGroup ?: url_session_manager_completion_group(), manager.completionQueue ?: dispatch_get_main_queue(), ^{
if (self.completionHandler) {
self.completionHandler(task.response, responseObject, serializationError);
} dispatch_async(dispatch_get_main_queue(), ^{
[[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingTaskDidCompleteNotification object:task userInfo:userInfo];
});
});
});
}
#pragma clang diagnostic pop
}

第25月第26天 dispatch_group_t dispatch_semaphore_t的更多相关文章

  1. 25. TABLESPACES , 26. TABLE_CONSTRAINTS , 27. TABLE_PRIVILEGES

    25. TABLESPACES TABLESPACES表提供有关活动MySQL Cluster表空间的信息. TABLESPACES表有以下列: TABLESPACE_NAME :表空间名称 ENGI ...

  2. 第26月第26天 Domain=AVFoundationErrorDomain Code=-11850

    1. curl -voa http://119.29.108.104:8080/inweb01/kotlin.mp4 -H "Range:bytes=0-1" https://al ...

  3. 第25月25日 urlsession

    1. private lazy var session: URLSession = { let configuration = URLSessionConfiguration.default conf ...

  4. 第25月第22日 django channels

    1. https://github.com/andrewgodwin/channels-examples/ https://channels.readthedocs.io/en/latest/

  5. 第25月第18天 vue

    1.cnpm sudo chown -R $USER /usr/local  npm install -g cnpm --registry=https://registry.npm.taobao.or ...

  6. 第25月第17天 django rest framwork authentication /tmp/mysql.sock

    1.authentication https://www.django-rest-framework.org/api-guide/authentication/#authentication 2.dj ...

  7. 第25月第15天 udacity cs253

    1.cs253 https://classroom.udacity.com/courses/cs253 webapp2 Install WebOb, Paste and webapp2¶ We nee ...

  8. 第25月第11天 deeplearning.ai

    1.网易云课堂 深度学习工程师 点击进入课程地址(英文)(收费) 点击进入课程地址(中文)(免费) 第一门 神经网络和深度学习 第二门 改善神经网络 第三门 结构化机器学习项目 第四门 卷积神经网络 ...

  9. 第25月第9天 tf_tang_poems kaggle

    1.neural-style https://github.com/anishathalye/neural-style wget http://www.vlfeat.org/matconvnet/mo ...

随机推荐

  1. mongoDB-Explain

    新版的MongoDB中的Explain已经变样了 Explain支持三种Mode queryPlanner Mode db.collection.explain() 默认mode是queryPlann ...

  2. Myeclipse启动报错:An error has occurred.See the log file

    出现这个问题是因为断电前myeclipse还在运行,日志报错如下: !ENTRY org.eclipse.osgi 4 0 2017-07-24 08:29:48.485 !MESSAGE An er ...

  3. 象棋start

    这篇文章其实谈的不是象棋开局,更谈不上开局技巧,举个例子:第一步走炮二平五,也即是中炮局,但中炮局可以根据对手的应对着法演变成很多,比如:五七炮对屏风马,五六炮对屏风马,顺炮局,以及雷公炮等等,这些才 ...

  4. Tennis Game CodeForces - 496D(唯一分解定理,费马大定理)

    Tennis Game CodeForces - 496D 通过排列组合解决问题. 首先两组不同素数的乘积,是互不相同的.这应该算是唯一分解定理的逆运用了. 然后是,输入中的素数,任意组合,就是n的因 ...

  5. 2.Diango学习

    ##创建应用 python manage.py startapp blog !!创建应用后要添加应用,名称不允许与模块名称相同 ##应用目录结构 ##文件介绍 1. 2. 3. 4. 5. 6. ## ...

  6. Mysq基础l数据库管理、表管理、增删改数据整理

    一.       数据库管理: 创建数据库: create database(自定义) 查询所有数据库: show databases;(查询所有数据库) show create database ( ...

  7. python IDLE颜色设置

    相信刚学习python的朋友们,都还是挺喜欢python自带的IDLE,但是白的代码背景色以及其它的代码色如何更改呢? Step1:找到config-Highlight.cfg文件,win在C:\Us ...

  8. Shell中变量扩展操作

    假设我们定义了一个变量为:file=/dir1/dir2/dir3/my.file.txt 可以用${ }分别替换得到不同的值:${file#*/}:删掉第一个 / 及其左边的字符串:dir1/dir ...

  9. Python的命名空间及作用域

    命名空间的分类 全局命名空间 是在程序从上到下被执行的过程中依次加载进内存的:放置了我们设置的所有变量名和函数名 局部命令空间 就是函数内部定义的名字:当调用函数的时候 才会产生这个名称空间 随着函数 ...

  10. Java NIO中的Buffer 详解

    Java NIO中的Buffer用于和NIO通道进行交互.如你所知,数据是从通道读入缓冲区,从缓冲区写入到通道中的.缓冲区本质上是一块可以写入数据,然后可以从中读取数据的内存.这块内存被包装成NIO ...