IOS开发之NSLock 的使用

时间:2023-02-01 00:11:48
在下面的例子中 使用 NSLock 使得 线程A,B,C, 依次执行;若不使用NSLock 则线程的执行是无序的<span style="font-family: Arial, Helvetica, sans-serif;">//    NSLock的执行原理:</span>
<span style="font-family: Arial, Helvetica, sans-serif;">//    某个线程A调用lock方法。这样,NSLock将被上锁。可以执行“关键部分”,完成后,调用unlock方法。</span>
//    如果,在线程A 调用unlock方法之前,另一个线程B调用了同一锁对象的lock方法。那么,线程B只有等待。直到线程A调用了unlock。
   
    NSLock* _lock = [[NSLock alloc] init];

    // ThreadA
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
    
        [_lock lock];
        
        [self performSelector:@selector(threadA) withObject:nil];
        sleep(5);
        
        [_lock unlock];
       
        
        
    });
    
    // ThreadB
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
        
         [_lock lock];
        [self performSelector:@selector(threadB) withObject:nil];
        sleep(5);
         [_lock unlock];
        
        
        
    });
    // ThreadC
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
        
         [_lock lock];
        [self performSelector:@selector(threadC) withObject:nil];
        sleep(5);
         [_lock unlock];
        
    });

}


- (void)threadA
{
    NSLog(@"name A: %@",[NSThread currentThread].name);

}

- (void)threadB
{
    NSLog(@"name B: %@",[NSThread currentThread].name);

}
- (void)threadC
{
    NSLog(@"name C: %@",[NSThread currentThread].name);
    
}