iOS development-Multithreaded development line Shuo

Source: Internet
Author: User
Tags gcd

A resource may be shared by multiple threads, that is, multiple threads may access the same piece of resources, such as multiple threads accessing the same object, the same variable, the same file, and the same method. Therefore, when multiple threads access the same piece of resources, it is easy to get data errors and data insecurity. So to avoid these problems, we need to use the "thread lock" to achieve.

This article focuses on how iOS creates Locks (summary):

First, the use of keywords

1)@synchronized (Mutual exclusion Lock)

Pros: Using the @synchronized keyword makes it easy to create a lock object without explicitly creating a lock object.

Disadvantage: An exception handler is implicitly added to protect the code, which automatically releases the mutex when the exception is thrown. While this implicit exception handling brings overhead to the system, you can use the lock object to optimize resources.

Second,"object-c" language

1) nslock (Mutual exclusion Lock)

2)Nsrecursivelock (recursive lock)

Conditional locks, recursive or cyclic methods use this method to implement a lock, which avoids deadlocks and other problems.

3) Nsconditionlock (conditional lock)

Use this method to specify that you can unlock only when the condition is met.

4) Nsdistributedlock (distributed lock)

There is no need for iOS, and there is no such method, so this article is not introduced, here to write just want to let everyone know that there is this lock.

If you want to learn nsdistributedlock, you can create a Mac OS project for your own walkthrough, method please Google, thank you.

Iii.C language

1)pthread_mutex_t (Mutual exclusion Lock)

2)gcd-Signal Volume ("Mutex")

3)pthread_cond_t (conditional lock)

Thread Safety--lock

First, the use of 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 sleeps 3 seconds     });//Thread Bdispatch_async (dispatch_get_global_queue (dispatch_queue_priority_default, 0), ^{    @synchronized (person) {        [person personb];    }});   

The use of the keyword @synchronized, the locked object is the unique identity of the lock, only the identity is the same, satisfies the mutex. If the thread B lock Object person is changed to self or another identity, then thread b will not be blocked. Whether you see @synchronized (self) is also true. It can lock any object, described as @synchronized (anobj).

Second, object-c language

1) using Nslock to implement the lock

//Instance class personPerson *person =[[Person alloc] init];//Create a lockNslock *mylock =[[Nslock alloc] init];//Thread ADispatch_async (Dispatch_get_global_queue (Dispatch_queue_priority_default,0), ^{[MyLockLock];    [Person PersonA]; [Nsthread sleepfortimeinterval:5]; [MyLock unlock];});//thread BDispatch_async (Dispatch_get_global_queue (Dispatch_queue_priority_default,0), ^{[MyLockLock];    [Person PERSONB]; [MyLock unlock];});

Program run Result: thread b waits for thread A to unlock before it executes thread b. If thread b removes the lock and unlock methods, then thread b will not be blocked, as is the case with synchronized . You need to use the same lock object to be mutually exclusive.

The Nslock class also provides the Trylock method, which means that attempts to lock, when the lock fails, does not block the process, but returns no. You can also use the lockbeforedate: method, which means that the lock is attempted before the specified time, and no is returned if it is not locked before the specified time .

Note: Locking (lock) and unlocking (UnLock) must be paired with

2) using the Nsrecursivelock class to implement the lock

//Instance class personPerson *person =[[Person alloc] init];//To Create a lock objectNsrecursivelock *thelock =[[Nsrecursivelock alloc] init];//To Create a recursive methodStatic void(^testcode) (int); Testcode= ^(intvalue)    {[Thelock trylock]; if(Value >0) {[Person PersonA]; [Nsthread sleepfortimeinterval:1]; Testcode (Value-1); } [Thelock unlock];};//Thread ADispatch_async (Dispatch_get_global_queue (Dispatch_queue_priority_default,0), ^{Testcode (5);});//thread BDispatch_async (Dispatch_get_global_queue (Dispatch_queue_priority_default,0), ^{[ThelockLock];    [Person PERSONB]; [Thelock unlock];});

if we put the Nsrecursivelock class is replaced by the Nslock class, then the program will deadlock. Because in this example, the recursive method causes the lock to be locked (lock) multiple times, so it is blocked. You can avoid this problem by using the Nsrecursivelock class.

3) Use the nsconditionlock (conditional Lock) class to implement the lock:

You can use this method to create a condition that specifies the unlock, and only if the condition is met.

//Instance class personPerson *person =[[Person alloc] init];//Create a conditional lockNsconditionlock *conditionlock =[[Nsconditionlock alloc] init];//Thread ADispatch_async (Dispatch_get_global_queue (Dispatch_queue_priority_default,0), ^{[ConditionlockLock];    [Person PersonA]; [Nsthread sleepfortimeinterval:5]; [Conditionlock unlockwithcondition:Ten];});//thread BDispatch_async (Dispatch_get_global_queue (Dispatch_queue_priority_default,0), ^{[Conditionlock lockwhencondition:Ten];    [Person PERSONB]; [Conditionlock unlock];});

Thread A uses the lock method, so it locks directly and specifies that only 10 of the cases are satisfied to unlock successfully.

Unlockwithcondition: Method, create conditional lock, parameter passed to "int". Lockwhencondition: The method is unlocked and is also a parameter that passes in an "integer".

Iii. C language

1) Use pthread_mutex_t implementation lock

Note: The header file must be imported: #import <pthread.h>

//Instance class personPerson *person =[[Person alloc] init];//To Create a lock object__block pthread_mutex_t Mutex;pthread_mutex_init (&mutex, NULL);//Thread ADispatch_async (Dispatch_get_global_queue (Dispatch_queue_priority_default,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 above example

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

GCD provides a mechanism for signaling the use of which we can create "locks" (semaphores and locks are differentiated, specifically please own Baidu).

//Instance class personPerson *person =[[Person alloc] init];//Create and set a volumedispatch_semaphore_t semaphore = Dispatch_semaphore_create (1);//Thread ADispatch_async (Dispatch_get_global_queue (Dispatch_queue_priority_default,0), ^{dispatch_semaphore_wait (semaphore, dispatch_time_forever);    [Person PersonA]; [Nsthread sleepfortimeinterval:5]; Dispatch_semaphore_signal (semaphore);});//thread BDispatch_async (Dispatch_get_global_queue (Dispatch_queue_priority_default,0), ^{dispatch_semaphore_wait (semaphore, dispatch_time_forever);    [Person PERSONB]; Dispatch_semaphore_signal (semaphore);});

The effect is also consistent with the example described above.

I'll explain the code here. The Dispatch_semaphore_wait method is to reduce the signal volume by 1 by adding 1,dispatch_semaphore_signal.

We think of the semaphore as a counter, and when the counter is a non-negative integer, all threads that pass through it should subtract this integer by 1. If the counter is greater than 0, then access is allowed and the counter is reduced by 1. If 0, access is forbidden, and all threads that pass through it are in a waiting state.

3) Create a lock using POSIX (conditional lock)

//Instance class personPerson *person =[[Person alloc] init];//Creating Mutex Locks__block pthread_mutex_t Mutex;pthread_mutex_init (&mutex, NULL);//Create a conditional lock__block pthread_cond_t Cond;pthread_cond_init (&cond, NULL);//Thread ADispatch_async (Dispatch_get_global_queue (Dispatch_queue_priority_default,0), ^{Pthread_mutex_lock (&mutex); Pthread_cond_wait (&cond, &mutex);    [Person PersonA]; Pthread_mutex_unlock (&( mutex);});//thread BDispatch_async (Dispatch_get_global_queue (Dispatch_queue_priority_default,0), ^{Pthread_mutex_lock (&mutex);    [Person PERSONB]; [Nsthread sleepfortimeinterval:5]; Pthread_cond_signal (&cond); Pthread_mutex_unlock (&( mutex);});

Effect: The program calls thread B first, and then calls thread a after 5 seconds. Thread B has an activation lock because it creates a wait condition lock, and thread A is activated only when thread B finishes executing.

The Pthread_cond_wait method is to wait for a conditional lock.

The Pthread_cond_signal method is to excite a condition lock of the same condition.

Simple summary:

In general, if the project is not big, we will steal a little lazy, directly using the keyword @synchronized to establish a lock, lazy method. Second, you can use the OC method provided by Apple, and then use C to build the lock.

This article refers to the article:

iOS multithreaded Development (iv)---Thread synchronization

Objective-c in different ways to achieve lock (i)

Semaphores and mutual exclusion lock

Blog Garveycalvin

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

This article copyright belongs to the author and the blog Garden altogether, welcome reprint, but must retain this paragraph statement, and gives the original link, thanks cooperation!

iOS development-Multithreaded development line Shuo

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.