标题:
iOS 中常见的几种锁-代码示例(2)
[打印本页]
作者:
look_w
时间:
2019-3-10 14:25
标题:
iOS 中常见的几种锁-代码示例(2)
2. iOS中的递归锁
同一个线程可以多次加锁,不会造成死锁
死锁->
- (void)lock5 {
NSLock *commonLock = [[NSLock alloc] init];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
static void (^XWRecursiveBlock)(int);
XWRecursiveBlock = ^(int value) {
[commonLock lock];
if (value > 0) {
NSLog(@"加锁层数: %d",value);
sleep(1);
XWRecursiveBlock(--value);
}
NSLog(@"程序退出!");
[commonLock unlock];
};
XWRecursiveBlock(3);
});
}
复制代码
<-死锁
2.1 NSRecursiveLock
- (void)lock4 {
NSRecursiveLock *recursiveLock = [[NSRecursiveLock alloc] init];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
static void (^XWRecursiveBlock)(int);
XWRecursiveBlock = ^(int value) {
[recursiveLock lock];
if (value > 0) {
NSLog(@"加锁层数: %d",value);
sleep(1);
XWRecursiveBlock(--value);
}
NSLog(@"程序退出!");
[recursiveLock unlock];
};
XWRecursiveBlock(3);
});
}
复制代码
2.2 pthread
- (void)lock6 {
__block pthread_mutex_t recursiveMutex;
pthread_mutexattr_t recursiveMutexattr;
pthread_mutexattr_init(&recursiveMutexattr);
pthread_mutexattr_settype(&recursiveMutexattr, PTHREAD_MUTEX_RECURSIVE);
pthread_mutex_init(&recursiveMutex, &recursiveMutexattr);
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
static void (^XWRecursiveBlock)(int);
XWRecursiveBlock = ^(int value) {
pthread_mutex_lock(&recursiveMutex);
if (value > 0) {
NSLog(@"加锁层数: %d",value);
sleep(1);
XWRecursiveBlock(--value);
}
NSLog(@"程序退出!");
pthread_mutex_unlock(&recursiveMutex);
};
XWRecursiveBlock(3);
});
}
欢迎光临 电子技术论坛_中国专业的电子工程师学习交流社区-中电网技术论坛 (http://bbs.eccn.com/)
Powered by Discuz! 7.0.0