IOS development-thread security for multi-thread Development

Source: Internet
Author: User

IOS development-thread security for multi-thread Development
A resource may be shared by multiple threads, that is, multiple threads may access the same resource, for example, multiple threads access the same object, the same variable, the same file, and the same method. Therefore, when multiple threads access the same resource, data errors and data insecurity may easily occur. To avoid these problems, we need to use the "thread lock. This article mainly discusses how to create a lock for IOS (summary): 1. Use keyword 1) @ synchronized (mutex lock) Advantages: You can easily create a Lock Object using the @ synchronized keyword, you do not need to explicitly create lock objects. Disadvantage: an implicit Exception Processing is added to protect the code. The mutex lock is automatically released when the exception is thrown. This implicit Exception Processing brings about additional system overhead. To optimize resources, you can use lock objects. Ii. "Object-C" language 1) NSLock (mutex lock) 2) NSRecursiveLock (recursive lock) condition lock. This method is used to implement the lock in recursive or cyclic methods, this prevents deadlocks and other issues. 3) NSConditionLock can be specified using this method, and can be unlocked only when the conditions are met. 4) NSDistributedLock (Distributed Lock) is not required or used in IOS. Therefore, this article does not introduce it. It is written here to let everyone know that this lock exists. If you want to learn about NSDistributedLock, you can create a mac OS project and perform self-testing. please Google the method yourself. Thank you. 3. C language 1) pthread_mutex_t (mutex lock) 2) GCD-semaphore ("mutex lock") 3) pthread_cond_t (condition lock) thread security-lock 1. Use keywords: 1) @ synchronized // instance class personPerson * person = [[Person alloc] init]; // thread Adispatch_async (dispatch_get_global_queue (queue, 0), ^ {@ synchronized (person) {[person personA]; [NSThread sleepForTimeInterval: 3]; // thread sleep for 3 seconds}); // thread Bdispatch_async (dispatch_get_global_queue (DISPATCH_QUEUE_PRIO RITY_DEFAULT, 0), ^{@ synchronized (person) {[person personB] ;}}); keyword @ synchronized usage, the locked object is the unique identifier of the lock, mutual Exclusion is met only when the IDs are the same. If the person of the thread B lock object is changed to self or another identifier, thread B will not be blocked. Is it true if you see @ synchronized (self. It can lock any object and describe @ synchronized (anObj ). Ii. Object-C language 1) Use NSLock to implement lock // instance class personPerson * person = [[Person alloc] init]; // create a lock NSLock * myLock = [[NSLock alloc] init]; // thread Adispatch_async (dispatch_get_global_queue (queue, 0), ^ {[myLock lock]; [person personA]; [NSThread sleepForTimeInterval: 5]; [myLock unlock] ;}); // thread Bdispatch_async (dispatch_get_global_queue (queue, 0), ^ {[myLock lock]; [Person personB]; [myLock unlock];}); program running result: thread B will wait until thread A is unlocked before it executes thread B. If thread B removes the lock and unlock methods, thread B will not be blocked. This is the same as synchronized and requires the same lock object to be mutually exclusive. The NSLock class also provides the tryLock method, which means to attempt to lock. When the lock fails, the process is not blocked, but NO is returned. You can also use the lockBeforeDate method, which means to try to lock before the specified time. If it cannot be locked before the specified time, NO is returned. Note: lock and unLock must be paired. 2) use the NSRecursiveLock class to implement the lock. // instance class personPerson * person = [[Person alloc] init]; // create a Lock Object NSRecursiveLock * theLock = [[NSRecursiveLock alloc] init]; // create a recursive method static void (^ testCode) (int); testCode = ^ (int value) {[theLock tryLock]; if (value> 0) {[person personA]; [NSThread sleepForTimeInterval: 1]; testCode (value-1);} [theLock unlock];}; // thread Adispatch_async (dispatch_get _ Global_queue (queue, 0), ^ {testCode (5) ;}); // thread Bdispatch_async (dispatch_get_global_queue (DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^ {[theLock lock]; [person personB]; [theLock unlock] ;}); if we change the NSRecursiveLock class to the NSLock class, the program will be deadlocked. In this example, the recursive method causes the Lock to be locked multiple times, and thus the Lock itself is blocked. This problem can be avoided by using the NSRecursiveLock class. 3) use the NSConditionLock (condition lock) class to implement the lock: You can use this method to create a condition that specifies the unlock. The lock can be unlocked only when the condition is met. // Instance class personPerson * person = [[Person alloc] init]; // create a condition lock NSConditionLock * conditionLock = [[NSConditionLock alloc] init]; // thread Adispatch_async (dispatch_get_global_queue (queue, 0), ^ {[conditionLock lock]; [person personA]; [NSThread sleepForTimeInterval: 5]; [conditionLock unlockWithCondition: 10];}); // thread Bdispatch_async (dispatch_get_global_queue (DISPATCH_QUEUE_PRIORITY _ DEFAULT, 0), ^ {[conditionLock lockWhenCondition: 10]; [person personB]; [conditionLock unlock] ;}); thread A uses the lock method, therefore, it will be locked directly, and the unlock can be successful only when 10 is specified. UnlockWithCondition: method, used to create a condition lock. The parameter is passed in as an "integer ". LockWhenCondition: Unlock the method and an integer parameter. 3. C language 1) Use pthread_mutex_t to implement the lock. Note: The header file must be imported: # import <pthread. h> // instance class personPerson * person = [[Person alloc] init]; // create a Lock Object _ block pthread_mutex_t mutex; pthread_mutex_init (& mutex, NULL ); // thread Adispatch_async (dispatch_get_global_queue (queue, 0), ^ {pthread_mutex_lock (& mutex); [person personA]; [NSThread sleepForTimeInterval: 5]; pthread_mutex_unlock (& mutex) ;}); // thread Bdispatch _ Async (dispatch_get_global_queue (DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^ {pthread_mutex_lock (& mutex); [person personB]; pthread_mutex_unlock (& mutex );}); the implementation effect is consistent with the previous example. 2) using GCD to implement the "lock" (semaphore) GCD provides a signal mechanism, we can use it to create a "Lock" (semaphores and locks are different, please Baidu ). // Instance class personPerson * person = [[Person alloc] init]; // create and set the message volume dispatch_semaphore_t semaphore = dispatch_semaphore_create (1); // thread Adispatch_async (Response (response, response, 0), ^ {threads (semaphore, threads); [person personA]; [NSThread sleepForTimeInterval: 5]; threads (semaphore) ;}); // thread Bdispatch_async (dispatch_get_g Lobal_queue (queue, 0), ^ {Queue (semaphore, DISPATCH_TIME_FOREVER); [person personB]; dispatch_semaphore_signal (semaphore) ;}); the effect is consistent with the previous example. I will explain the code here. The dispatch_semaphore_wait method is to add 1 to the semaphore, and dispatch_semaphore_signal is to subtract 1 from the semaphore. We regard semaphores as a counter. When the counter is a non-negative integer, all threads passing through it should subtract this integer by 1. If the counter is greater than 0, access is allowed and the counter is reduced by 1. If it is 0, the access is forbidden, and all threads passing through it are in the waiting state. 3) Use POSIX (condition lock) to create a lock // instance class personPerson * person = [[Person alloc] init]; // create a mutex lock _ block pthread_mutex_t mutex; pthread_mutex_init (& mutex, NULL); // create a condition lock _ block pthread_cond_t cond; pthread_cond_init (& cond, NULL); // thread Adispatch_async (callback (success, 0 ), ^ {pthread_mutex_lock (& mutex); pthread_cond_wait (& cond, & mutex); [person personA]; pthread_mutex_unlock (& mu Tex) ;}); // thread Bdispatch_async (dispatch_get_global_queue (queue, 0), ^ {pthread_mutex_lock (& mutex); [person personB]; [NSThread sleepForTimeInterval: 5]; pthread_cond_signal (& cond); pthread_mutex_unlock (& mutex) ;}); effect: the program will first call thread B and then call thread A five seconds later. Because A waiting condition lock is created in thread A, thread B has an activation lock, and thread A is activated only after thread B completes execution. The pthread_cond_wait method is a waiting condition lock. The pthread_cond_signal method is used to activate a conditional lock with the same conditions. Summary: In general, if the project is not large, we will be a little lazy and directly use the keyword @ synchronized to create the lock and lazy method. Next, you can use the OC method provided by Apple to establish a lock using C.

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.