[ad_1]
I’ve some code not thread secure, So I attempted to make use of NSRecursiveLock to forestall my work queue and most important thread entry some properties on the identical time. I create two work queue(work queue and wait queue), work queue to do some heavy work. So as to stop block most important thread, I create one other wait queue to attend the lock, so I can async to most important thread after I get the lock.
I face two downside:
- after the work queue unlock, wait queue nonetheless ready.
- code will get two form of output
I believe the output ought to be
1. work queue get lock
2. wait queue wait lock
3. put up notification from work queue
noti known as
unlock
get lock
4. most important thread do work
however I get Output:
[Output 1]
1. work queue get lock
2. wait queue wait lock
3. put up notification from work queue
noti known as
unlock
[Output 2]
1. work queue get lock
2. wait queue wait lock
get lock
4. most important thread do work
3. put up notification from work queue
noti known as
unlock

@interface ViewController ()
@property (nonatomic) NSLock *lock;
@property (nonatomic) NSRecursiveLock *recursiveLock;
@property (nonatomic) dispatch_queue_t queue;
@property (nonatomic) dispatch_queue_t lockWaitQueue;
@finish
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
_queue = dispatch_queue_create("serial", DISPATCH_QUEUE_SERIAL);
_lockWaitQueue = dispatch_queue_create("wait_queue", DISPATCH_QUEUE_SERIAL);
[[NSNotificationCenter defaultCenter] addObserverForName:@"noti" object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull notice) {
NSLog(@"noti known as");
}];
_lock = [NSLock new];
_recursiveLock = [NSRecursiveLock new];
[self tryFixDeadLockCace];
}
- (void)tryFixDeadLockCace {
NSRecursiveLock *lock = _recursiveLock;
dispatch_queue_t queue = _queue;
dispatch_queue_t lockWaitQueue = _lockWaitQueue;
NSLog(@"1. work queue get lock");
dispatch_async(queue, ^{
[lock lock];
dispatch_async(dispatch_get_main_queue(), ^{
dispatch_async(lockWaitQueue, ^{
NSLog(@"2. wait queue wait lock");
[lock lock];
NSLog(@"get lock");
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"4. most important thread do work");
[lock unlock];
});
});
});
});
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), queue, ^{
NSLog(@"3. put up notification from work queue");
[[NSNotificationCenter defaultCenter] postNotificationName:@"noti" object:nil];
NSLog(@"unlock");
[lock unlock];
});
}
- (void)noti {
}
@finish
[ad_2]
