-
synchronized
static NSString* A = @"A";/** B鎖 /
static NSString B = @"B";
dispatch_async(queue, ^{
// NSLog(@"%@",[self sourceOut]) ;
@synchronized(A){
NSLog(@"鎖A0");
sleep(2);
@synchronized(B){
NSLog(@"鎖B0");
}
}
});dispatch_async(queue, ^{
@synchronized(B){
NSLog(@"鎖B1");@synchronized(A){ NSLog(@"鎖A1"); } }
});
打铀稀:2018-04-06 15:35:56.206903+0800 COCOCOCO[13309:566143] 鎖A0
2018-04-06 15:35:56.206939+0800 COCOCOCO[13309:566145] 鎖B1
- NSLock
[self.lock lock];
[self.lock lock];//由于當(dāng)前線程加鎖佳头,現(xiàn)在再次加同樣的鎖,需等待當(dāng)前線程解鎖晴氨,把當(dāng)前線程掛起畜晰,不能解鎖
[_lock unlock];
[_lock unlock];
- 遞歸鎖。 核心:允許同一個(gè)線程對(duì)一把鎖進(jìn)行重復(fù)加鎖瑞筐。 如果不是同一線程那么將死鎖
-
(void)__initMutexLock:(pthread_mutex_t *)mutex{
// 遞歸鎖:允許同一個(gè)線程對(duì)一把鎖進(jìn)行重復(fù)加鎖// 初始化屬性
pthread_mutexattr_t attr;
pthread_mutexattr_init(&attr);
pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
// 初始化鎖
pthread_mutex_init(mutex, &attr);
// 銷毀屬性
pthread_mutexattr_destroy(&attr);
}
-
(void)viewDidLoad {
[super viewDidLoad];[self __initMutexLock:&_MutexLock];
dispatch_async(dispatch_get_global_queue(0, 0), ^{
pthread_mutex_lock(&_MutexLock);
NSLog(@"加鎖 %s =11111== %@",func, [NSThread currentThread]);dispatch_sync(dispatch_get_main_queue(), ^{ pthread_mutex_lock(&_MutexLock); NSLog(@"加鎖 %s =22222== %@",__func__, [NSThread currentThread]); NSLog(@"解鎖 %s ==2222222= %@",__func__, [NSThread currentThread]); pthread_mutex_unlock(&_MutexLock); }); NSLog(@"解鎖 %s ==11111111= %@",__func__, [NSThread currentThread]); pthread_mutex_unlock(&_MutexLock);
});
}
2020-12-30 19:34:27.331898+0800 iOS-LockDemo[19500:315177] 加鎖 -[ViewController viewDidLoad]_block_invoke =11111== <NSThread: 0x600002d107c0>{number = 5, name = (null)}