IOS concurrent programming-eight locking methods and Comparison

Source: Internet
Author: User

IOS concurrent programming-eight locking methods and Comparison

In iOS development, it is inevitable that you will encounter locking. Today we will compare various locking methods.

Currently, I know the following locking methods:
1. @ synchronized keyword locking
2. NSLock object lock
3. NSCondition
4. NSConditionLock condition lock
5. NSRecursiveLock recursive lock
6. pthread_mutex mutex lock (C language)
7. Implement locking (GCD) for dispatch_semaphore semaphores)
8. OSSpinLock

Here, you can lock and unlock 10 million times in eight ways. The execution method is as follows:

# Import
  
   
# Import
   
    
-(Void) runLock {CFTimeInterval timeBefore; CFTimeInterval timeCurrent; NSUInteger I; NSUInteger count = 1000*10000; // execute 10 million times // @ synchronized id obj = [[NSObject alloc] init]; timeBefore = CFAbsoluteTimeGetCurrent (); for (I = 0; I
    
   
  

Execution result:

The figure shows that:
OSSpinLock has the best performance, and the dispatch_semaphore of GCD follows closely;
NSConditionLock and @ synchronized have poor performance;

PS:
1. it should be noted that this is only a test of the performance of direct Lock and Unlock for various locks. The usage conditions of some locks are slightly different, for example, NSLock and other methods such as tryLock are used for locking, and the functions of different Object locks are different. If you are interested, you can search one by one and further study the differences between different locks.
2. In addition, in general, the client rarely has such a large number of lock and unlock operations, so the performance of these locks can meet the needs of daily use.

 

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.