基于上一章节,介绍os_unfair_lock的用法
1、OSUnfairLock.h文件
#import "BaseLockViewController.h"
NS_ASSUME_NONNULL_BEGIN
@interface OSUnfairLock : BaseLockViewController
@end
NS_ASSUME_NONNULL_END
OSUnfairLock.m文件
#import "OSUnfairLock.h"
#import <os/lock.h>
@interface OSUnfairLock ()
//
@property (assign, nonatomic) os_unfair_lock lock1;
@property (assign, nonatomic) os_unfair_lock lock2;
@end
@implementation OSUnfairLock
- (void)viewDidLoad {
[super viewDidLoad];
self.lock1 = OS_UNFAIR_LOCK_INIT;
self.lock2 = OS_UNFAIR_LOCK_INIT;
[self concurrentMoney];
[self concurrentSaleTicket];
}
- (void)__saveMoney {
os_unfair_lock_lock(&_lock1);
[super saveMoney];
os_unfair_lock_unlock(&_lock1);
}
- (void)__drawMoney {
os_unfair_lock_lock(&_lock1);
[super drawMoney];
os_unfair_lock_unlock(&_lock1);
}
- (void)__saleTicket {
os_unfair_lock_lock(&_lock2);
[super saleTicket];
os_unfair_lock_unlock(&_lock2);
}
- (void)concurrentMoney {
dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
dispatch_async(queue, ^{
for (int i = 0; i < 10; i++) {
[self __saveMoney];
}
});
dispatch_async(queue, ^{
for (int i = 0; i < 10; i++) {
[self __drawMoney];
}
});
}
- (void)concurrentSaleTicket {
dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
dispatch_async(queue, ^{
for (int i = 0; i < 5; i++) {
[self __saleTicket];
}
});
dispatch_async(queue, ^{
for (int i = 0; i < 5; i++) {
[self __saleTicket];
}
});
}
@end