递归锁 死锁。

  1. 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

  1. NSLock
    [self.lock lock];
    [self.lock lock];//由于当前线程加锁,现在再次加同样的锁,需等待当前线程解锁,把当前线程挂起,不能解锁
    [_lock unlock];
    [_lock unlock];
  1. 递归锁。 核心:允许同一个线程对一把锁进行重复加锁。 如果不是同一线程那么将死锁
  • (void)__initMutexLock:(pthread_mutex_t *)mutex{
    // 递归锁:允许同一个线程对一把锁进行重复加锁

    // 初始化属性
    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== {number = 5, name = (null)}

你可能感兴趣的:(递归锁 死锁。)