- 信號量的使用:
//生成信號量
dispatch_semaphore_t semaphore = dispatch_semaphore_create(10);
//當(dāng)信號量為0的時候會永久等待
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
//信號量加一
dispatch_semaphore_signal(semaphore);
- 信號量使用的業(yè)務(wù)場景:
一、鎖
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賦值携茂,代碼有點(diǎn)長,就不貼了
dispatch_semaphore_signal(semaphore);
}];
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
return tasks;
}
三带膜、控制并發(fā)量,降低性能式廷。
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);
});
}