dispatch_semaphore

参考文章在GCD中,我们通常使用dispatch_semaphore来处理并发控制,
semaphore主要有三个函数操作分别是:

dispatch_semaphore_create    //创建semaphore,此时可以传入一个初始的信号量值

dispatch_semaphore_signal     //发送一个信号,当信号量被发送后,semaphore中的计数会加1

dispatch_semaphore_wait      // 等待信号,会使semaphore的计数减1,当semaphore中的计数小于0时,线程会被阻塞,直至计数大于0

总结就是dispatch_semaphore_signal发送一个信号,使得信号总量加1,dispatch_semaphore_wait等待信号,当信号总量小于0时会一直等待,否则可以正常运行并让信号量减1,
dispatch_group_t group = dispatch_group_create();
dispatch_semaphore_t semaphore = dispatch_semaphore_create(10);
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0);
for(in i = 0; i < 100; i++) {
dispatch_semaphore_wait(semaphore,DISPATCH_TIME_FOREVER);
dispatch_group_async(group,queue,^{
NSLog(@"%i",i);
sleep(2);
dispatch_semaphore_signal(semaphore);
});
}
dispatch_group_wait(group,DISPATCH_TIME_FOREVER);

当初始化时设置信号量为1时就可以当做资源锁来使用.在没有等待情况出现时,其性能比OSSpinLock自旋锁还要高。但是一旦有等待情况出现时,其性能会下降很多。
+ (nullable instancetype)classInfoWithClass:(Class)cls {
//1.类缓存
static CFMutableDictionaryRef classCache;
//2.资源锁
static dispatch_semaphore_t lock;
//3.创建单例
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
classCache = CFDictionaryCreateMutable(CFAllocatorGetDefault(), 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
lock = dispatch_semaphore_create(1);
});
//4.加锁并取出缓存的类信息
dispatch_semaphore_wait(lock, DISPATCH_TIME_FOREVER);
XRClassInfo info = CFDictionaryGetValue(classCache, (__bridge const void )(cls));
dispatch_semaphore_signal(lock);
//5.如果没有缓存的类信息,则需要重新创建,并缓存
if(!info) {
//6.根据类,创建新的类信息
info = [[XRClassInfo alloc] initWithClass:cls];
if(info) {
dispatch_semaphore_wait(lock, DISPATCH_TIME_FOREVER);
CFDictionarySetValue(classCache, (bridge const void *)(cls), (bridge const void *)(info));
dispatch_semaphore_signal(lock);
}
}
return info;
}

欢迎大家关注我的微信公众号

wechat.jpg
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值