- 信号量的使用:
//生成信号量
dispatch_semaphore_t semaphore = dispatch_semaphore_create(10);
//当信号量为0的时候会永久等待
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
//信号量加一
dispatch_semaphore_signal(semaphore);
- 信号量使用的业务场景:
一、锁
YYKit加锁代码:
- (instancetype)init {
self = [super init];
_lock = dispatch_semaphore_create(1);
return self;
}
- (NSURL *)imageURL {
dispatch_semaphore_wait(_lock, DISPATCH_TIME_FOREVER);
NSURL *imageURL = _imageURL;
dispatch_semaphore_signal(_lock);
return imageURL;
}
二、异步返回
- (NSArray *)tasksForKeyPath:(NSString *)keyPath {
__block NSArray *tasks = nil;
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
[self.session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
//task赋值,代码有点长,就不贴了
dispatch_semaphore_signal(semaphore);
}];
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
return tasks;
}
三、控制并发量,降低性能。
dispatch_semaphore_t semaphore = dispatch_semaphore_create(5);
for (int i = 0; i < 1000; ++i) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
//多线程代码
dispatch_semaphore_signal(semaphore);
});
}
网友评论