Common iOS lock Methods
Lock usage
There are several methods in iOS to solve the problem of mutex synchronization when multiple threads access the same memory address:
Method 1, @ synchronized (id anObject), (simplest method)
The parameter object is automatically locked to ensure the code thread security in the critical section.
@ Synchronized (self) {// This code is mutually exclusive to other @ synchronized (self). // self points to the same object}
Method 2: NSLock
The NSLock object implements NSLocking protocol, which includes several methods:
Lock, lock
Unlock, unlock
TryLock, attempts to lock. If the lock fails, the thread is not blocked, but NO is returned immediately.
LockBeforeDate: temporarily blocks the thread before the specified date (if NO lock is obtained). If NO lock is obtained after expiration, the thread is awakened and the function immediately returns NO
For example:
NSLock *theLock = [[NSLock alloc] init]; if ([theLock lock]) { //do something here [theLock unlock]; }
Method 3: NSRecursiveLock, recursive lock
NSRecursiveLock, multiple calls will not block the thread that has obtained the lock.
NSRecursiveLock *theLock = [[NSRecursiveLock alloc] init]; void MyRecursiveFunction(int value) { [theLock lock]; if (value != 0){ –value; MyRecursiveFunction(value); } [theLock unlock]; } MyRecursiveFunction(5);
Method 4: NSConditionLock
NSConditionLock, condition lock. You can set conditions.
// Public part id condLock = [[NSConditionLock alloc] initWithCondition: NO_DATA]; // thread 1, producer while (true) {[condLock lockWhenCondition: NO_DATA]; // production data [condLock unlockWithCondition: HAS_DATA];} // thread 2, Consumer while (true) {[condLock lockWhenCondition: HAS_DATA]; // consume [condLock unlockWithCondition: NO_DATA];}
Method 5: NSDistributedLock
NSDistributedLock, distribution lock, file implementation, cross-Process
Use tryLock to obtain the lock.
Use the unlock method to release the lock.
If a process to obtain the lock fails before the lock is released, the lock will never be released. In this case, you can use breakLock to forcibly obtain the lock.