IOS development-thread security for multi-threaded Development

Source: Internet
Author: User

IOS development-thread security for multi-threaded 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 describes how to create a lock for IOS (summary ):

I. Use keywords

1) @ synchronized (mutex lock)

Advantage: The @ synchronized keyword can be used to easily create lock objects without explicitly creating 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)

Conditional lock: This method is used to implement the lock when recursive or cyclic methods are used to avoid problems such as deadlocks.

3) NSConditionLock (condition lock)

You can use this method to specify that the unlock can be unlocked only when the conditions are met.

4) NSDistributedLock (Distributed Lock)

This method 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.

C Language

1) pthread_mutex_t (mutex lock)

2) GCD-semaphore ("mutex lock ")

3) pthread_cond_t (condition lock)

 

Thread security-Lock

I. Use keywords:

1) @ synchronized

// Instance class personPerson * person = [[Person alloc] init]; // thread Adispatch_async (dispatch_get_global_queue (DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^ {@ synchronized (person) {[person personA]; [NSThread sleepForTimeInterval: 3]; // thread sleep for 3 seconds}); // thread Bdispatch_async (dispatch_get_global_queue (DISPATCH_QUEUE_PRIORITY_DEFAULT, 0 ), ^ {@ synchronized (person) {[person personB] ;}});

Keyword @ synchronized: The locked object is the unique identifier of the lock. Only when the same identifier is used can the lock be mutually exclusive. 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 the lock

// Instance class personPerson * person = [[Person alloc] init]; // create the 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 (DISPATCH_QUEUE_PRIORITY_DEFAULT, 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 used together.

 

2) use the NSRecursiveLock class to implement the lock 

// Instance class personPerson * person = [[Person alloc] init]; // create the 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 replace the NSRecursiveLock class with 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 class to implement the lock:

You can use this method to create a specified unlocking condition. A 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 (bytes, 0), ^ {[conditionLock lockWhenCondition: 10]; [person personB]; [conditionLock unlock];});

Thread A uses the lock method, so it will be locked directly, and it specifies that only 10 of the conditions can be successfully unlocked.

UnlockWithCondition: method, used to create a condition lock. The parameter is passed in as an "integer ". LockWhenCondition: Unlock the method and an integer parameter.

 

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 the 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 (queue, 0), ^ {pthread_mutex_lock (& mutex); [person personB]; pthread_mutex_unlock (& mutex );});

The implementation result is consistent with the previous example.

2) use GCD to implement "lock" (semaphore)

GCD provides a signal mechanism that we can use to create a "Lock" (semaphores and locks are different, please Baidu for details ).

// 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), ^ {separator (semaphore, DISPATCH_TIME_FOREVER); [person personA]; [NSThread sleepForTimeInterval: 5]; dispatch_semaphore_signal (semaphore );}); // thread Bdispatch_async (bytes, 0), ^ {bytes (semaphore, DISPATCH_TIME_FOREVER); [person personB]; dispatch_semaphore_signal (semaphore );});

The results are also consistent with those described in 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 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); // The thread Adispatch_async (equals, 0), ^ {pthread_mutex_lock (& mutex ); pthread_cond_wait (& cond, & mutex); [person personA]; pthread_mutex_unlock (& mutex) ;}); // 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, lazy method. Next, you can use the OC method provided by Apple to establish a lock using C.

 

 

 

 

References:

IOS multi-thread development (4) --- Thread Synchronization

Implement locks in different methods in Objective-C (1)

Semaphores and mutex

 

 

 

Blog Author: GarveyCalvin

Blog Source: http://www.cnblogs.com/GarveyCalvin/

The copyright of this article is shared by the author and the blog. You are welcome to repost it, but you must keep this statement and provide the original article link. Thank you for your cooperation!

 

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.