@synchronized和NSLock產生死鎖場景
阿新 • • 發佈:2018-12-04
NSLock:/** A鎖 */ 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
[self.lock lock];
[self.lock lock];//由於當前執行緒加鎖,現在再次加同樣的鎖,需等待當前執行緒解鎖,把當前執行緒掛起,不能解鎖
[_lock unlock];
[_lock unlock];
另附兩篇部落格:https://blog.csdn.net/hopedark/article/details/49640939
http://www.cocoachina.com/ios/20161205/18279.html