Use of various locks in iOS/Mac Development

Source: Internet
Author: User

Use of various locks in iOS/Mac Development
NSRecursiveLock recursive lock
The so-called recursive lock means that the lock can be reentrant on the same thread. It is equivalent to a common mutex lock for different threads. The lock defined by the NSRecursiveLock class can be locked multiple times in the same thread without causing a deadlock. Recursive locks track how many times it is locked. Each successful lock must call the unlock operation in balance. Only when all lock and unlock operations are balanced can the lock be truly released to other threads.

NSRecursiveLock * lock = [[NSRecursiveLock alloc] init]; // open a thread dispatch_async (idle, 0), ^ {static void (^ RecursiveMethod) (int ); recursiveMethod = ^ (int value) {[lock]; // start the recursive lock if (value> 0) {NSLog (@ value = % d, value ); sleep (2); RecursiveMethod (value-1);} [lock unlock]; // disable recursive lock}; RecursiveMethod (5 );}); // open another thread dispatch_async (dispatch_get_global_queue (queue, 0), ^ {sleep (2); // determine the status of the current lock BOOL flag = [lock lockBeforeDate: [NSDate dateWithTimeIntervalSinceNow: 1]; if (flag) {NSLog (@ lock before date); [lock unlock];} else {NSLog (@ fail to lock before date );}});

Code analysis: the first asynchronous dispatch creates a new thread and adds a recursive lock. In this case, the current recursive lock status is determined in the new thread created by the second asynchronous dispatch.
2. NSConditionLock condition lock
Common mutex locks and recursive locks only consider locks and locks. Such locks cannot meet various requirements of multiple threads for accessing shared resources. Therefore, the emergence of the conditional lock can solve the scenario where the special conditions must be met in multithreading technology to unlock some locks.

// NSConditionLock * conditionLock = [[NSConditionLock alloc] init]; // asynchronous thread 1 dispatch_async (dispatch_get_global_queue (queue, 0), ^ {for (int I = 0; I <= 2; I ++) {// create a conditional lock [conditionLock lock]; NSLog (@ thread1: % d, I); sleep (2 ); [conditionLock unlockWithCondition: I] ;}}); // asynchronous thread 2dispatch_async (dispatch_get_global_queue (queue, 0), ^ {// set a condition lock, corresponding unlockWithCondition: 2 To unlock [conditionLock lockWhenCondition: 2]; NSLog (@ thread2); [conditionLock unlock];});

Code Analysis: asynchronous thread 1 creates a condition lock without unlocking conditions, while asynchronous thread 2 concurrently creates a condition lock with the unlocking condition of 2, when the loop variable I in thread 1 is 2, the condition lock in thread 2 is unlocked.
3. NSDistributedLock Distributed Lock
When multiple processes or programs need to build mutually exclusive scenarios, the above multi-thread locks cannot meet the requirements. In this case, distributed locks must be used. Distributed locks are implemented through the file system. They do not inherit from NSLock and therefore do not implement the lock method. However, they provide methods such as tryLock, unlock, and breakLock. If you need to lock, you must implement a trylock round-robin.
Application:

Dispatch_async (dispatch_get_global_queue (DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^ {// The lock NSDistributedLock * lock = [[NSDistributedLock alloc] initWithPath: @/Users/mac/Desktop/earning _]; [lock breakLock]; [lock tryLock]; sleep (10); [lock unlock]; NSLog (@ appA: OK );});

Application B:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{       NSDistributedLock *lock = [[NSDistributedLock alloc] initWithPath:@/Users/mac/Desktop/earning__];        while (![lock tryLock]) {            NSLog(@appB: waiting);            sleep(1);        }        [lock unlock];        NSLog(@appB: OK);    });

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.