dispatch_semaphore是GCD中的信号量,可以处理多线程中线程并发的问题,也可以用作同步处理
一、dispatch_semaphore方法
创建信号量,里面的参数是表示信号的总量,值必须>=0
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
发送一个信号,信号量的总数会+1
dispatch_semaphore_signal(semaphore);
信号等待,当信号量的总数<=0的时候,会一直等待,直到信号量的总数>0的时候才会继续下面的执行
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
注意:dispatch_semaphore_wait
当信号量的总数<=0时候,该函数所在的线程就会等待,而信号量的总数>0的时候,该函数就会继续往下执行,同时信号量的总数-1
这里有个等待时间的参数,如果在等待的时间内获得了信号量,那么函数继续往下执行,如果等待时间内信号量一直为0,那么函数也会继续往下执行了
二、代码
实例一:信号量基本用法
- (void)test2 {
//信号量
//创建总数为10的信号量
dispatch_semaphore_t semaphore = dispatch_semaphore_create(10);
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
for (int i = 0; i < 100; i++) {
//这里注意当等待时间为10和1的线程的区别
dispatch_time_t time = dispatch_time(DISPATCH_TIME_NOW, 10);
//信号量总数>0,继续执行,否则等待
dispatch_semaphore_wait(semaphore, time);
dispatch_async(queue, ^{
NSLog(@"%i~~~~~%@",i, [NSThread currentThread]);
sleep(3);
//发送信号,信号量总数+1
dispatch_semaphore_signal(semaphore);
});
}
}
实例二:使用NSURLSession同步请求(使用信号量)
- (void)test3 {
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:@"http://imgsrc.baidu.com/forum/w%3D580/sign=16ccb289970a304e5222a0f2e1caa7c3/4ee3cc5c10385343102141ac9313b07ec880889f.jpg"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30];
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
NSURLSessionTask *dataTask = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSLog(@"~~~~~~下载完成了呢");
//发送信号
dispatch_semaphore_signal(semaphore);
}];
[dataTask resume];
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
NSLog(@"~~~~~~哈哈哈任务结束了呢");
}
实例三:使用NSURLSession同步请求(使用group)
- (void)test4 {
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:@"http://imgsrc.baidu.com/forum/w%3D580/sign=16ccb289970a304e5222a0f2e1caa7c3/4ee3cc5c10385343102141ac9313b07ec880889f.jpg"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30];
dispatch_group_t group = dispatch_group_create();
dispatch_queue_t queue = dispatch_queue_create("queue", DISPATCH_QUEUE_CONCURRENT);
//进入组
dispatch_group_enter(group);
dispatch_group_async(group, queue, ^{
NSURLSessionTask *dataTask = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSLog(@"~~~~~~下载完成了呢");
//离开组
dispatch_group_leave(group);
}];
[dataTask resume];
});
//等待组内的任务完成
dispatch_group_wait(group, DISPATCH_TIME_FOREVER);
NSLog(@"~~~~~~哈哈哈任务结束了呢");
}