Explanation of iOS Multithread Lock Mutual Exclusion Synchronization

  • 2021-08-31 09:27:51
  • OfStack

In iOS, there are several methods to solve the mutual exclusive synchronization problem of multithreaded access to the same memory address:

Method 1, @ synchronized (id anObject), (the simplest method)

The parameter object is automatically locked to ensure the thread safety of the code in the critical area


@synchronized(self) 
 
{ 
 
    //  This code has an effect on other  @synchronized(self)  They are mutually exclusive      
 
    // self  Point to the same 1 Objects  
 
}  

Method 2, NSLock
The NSLock object implements NSLocking protocol and contains several methods:

lock, Lock unlock, Unlock tryLock, an attempt to lock, if it fails, does not block the thread, but returns NO immediately lockBeforeDate: Temporarily blocks the thread before the specified date (if the lock is not acquired). If the lock is not acquired by the expiration date, 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 do not block the thread that has acquired the lock.


 NSRecursiveLock *theLock = [[NSRecursiveLock alloc] init];  
 void MyRecursiveFunction(int value)  
{  
 [theLock lock];  
 if (value != 0)  
<span style="font-size:14px;"> </span>{  
   In fact, in fact, the value;  
  MyRecursiveFunction(value);  
 } 
 [theLock unlock];  
}  
 
 MyRecursiveFunction(5); 

Method 4, NSConditionLock, conditional lock

NSConditionLock, condition lock, condition can be set


// 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 , consumers  
 while (true) {  
    [condLock lockWhenCondition:HAS_DATA];  
    // Consumption  
    [condLock unlockWithCondition:NO_DATA];  
} 

Method 5, NSDistributedLock, distributed lock

NSDistributedLock, distributed lock, file implementation, can cross-process

Use the tryLock method to acquire the lock.
Release the lock using the unlock method.

If a lock acquiring process hangs up before releasing the lock, the lock will not be released. At this time, the lock can be forcibly acquired through breakLock.


Related articles: