iOS thread sync and lock

Source: Internet
Author: User
Tags posix


The presence of multiple threads within an application raises several potential issues for thread-safe access to resources. Two threads simultaneously modifying the same resource can interfere with each other in unexpected ways.


IOS Provides a tool for you to use multiple sync tools, from the tools that provide mutually exclusive access to your program's ordered events. The following sections describe the resources for these tools and how to use them in code to affect secure access to programs.


We use the same example to illustrate these locks , when a variable array is manipulated when the two lines are Chengtong, a thread-safe problem exists when one of the threads adds data and a thread deletes the data, similar to a production consumer pattern ;


Use POSIX Mutual exclusion Lock

__block pthread_mutex_t Mutex;    Pthread_mutex_init (&mutex,null);    __block nsmutablearray* products = [[Nsmutablearray alloc]init];        Dispatch_async (Dispatch_get_global_queue (dispatch_queue_priority_default, 0), ^{while                (YES) {                        Pthread_ Mutex_lock (&mutex);            [Products addobject:@ "product"];                        Pthread_mutex_unlock (&mutex);        }            });        Dispatch_async (Dispatch_get_global_queue (dispatch_queue_priority_default, 0), ^{while                (YES) {            Pthread_ Mutex_lock (&mutex);            if (Products.count! = 0) {                [products removeobjectatindex:0];            }                        Pthread_mutex_unlock (&mutex);                    }            });


Use Nslock class

in theCocoain the programNslocka simple mutex is implemented in the all locks (including nslock) interface is actually all through the nslocking defined by the protocol, it defines the Lock and the Unlock method . You use these methods to obtain and release the lock.

In addition to the standard Locking behavior,Nslockclass also adds aTrylockand thelockbeforedate:method. MethodTrylockan attempt was made to acquire a lock, but it does not block the thread if the lock is not available. Instead, it just returnsNO. andlockbeforedate:method attempts to acquire a lock, but if the lock is not obtained within the specified time, it causes the thread to become non-blocking from the blocking state (or returnNO).

nslock* lock = [[Nslock alloc]init];    __block nsmutablearray* products = [[Nsmutablearray alloc]init];        Dispatch_async (Dispatch_get_global_queue (dispatch_queue_priority_default, 0), ^{while                (YES) {            [lock lock];            [Products addobject:@ "product"];                        [Lock unlock];                        /* Avoid blocking            *            /* if ([lock Trylock])            {                [Products addobject:@ "product"];                                [Lock unlock];            }             */        }                            });        Dispatch_async (Dispatch_get_global_queue (dispatch_queue_priority_default, 0), ^{while                (YES) {            [lock lock ];            if (Products.count! = 0) {                [products removeobjectatindex:0];            }                        [Lock unlock];                    }            });

Use @synchronized instruction

@synchronized directive is in objective-c a convenient way to create a mutex in your code. @synchronized directives do the same work as other mutexes (it prevents different threads from acquiring the same lock at the same time). In this case, however, you do not need to create a mutex or lock object directly. Instead, you simply need to use the objective-c Object as a token of the lock

__block nsmutablearray* products = [[Nsmutablearray alloc]init];        Dispatch_async (Dispatch_get_global_queue (dispatch_queue_priority_default, 0), ^{                @synchronized (Products)        {            while (YES) {                [Products addobject:@ "Product"];}}            );        Dispatch_async (Dispatch_get_global_queue (dispatch_queue_priority_default, 0), ^{                @synchronized (Products)        {while            (YES) {                if (products.count! = 0) {                    [Products Removelastobject];}}}            );


When using a single case

@interface Singleobject:nsobject@property (Strong, Nonatomic) Nsmutablearray *products;+ (instancetype) sharedinstance;-(void) addmethod;-(void) Removemethod; @end @implementation singleobject+ (instancetype) sharedinstance{    static Singleobject *sharedinstance_ = nil;    Static dispatch_once_t oncepredicate;    Dispatch_once (&oncepredicate, ^{        sharedinstance_ = [[[Self class] alloc] init];    });        return sharedinstance_;} -(ID) init{self    = [super init];    if (self)    {        self.products = [[Nsmutablearray alloc]init];    }        return self;} -(void) addmethod{    [self.products addobject:@ "Product"];} -(void) removemethod{    if (self.products.count! = 0) {        [self.products removeobjectatindex:0];}    } @end

Singleobject *object = [Singleobject sharedinstance];        Dispatch_async (Dispatch_get_global_queue (dispatch_queue_priority_default, 0), ^{                @synchronized (object)        {            while (YES) {                                [object Addmethod];}}}            );        Dispatch_async (Dispatch_get_global_queue (dispatch_queue_priority_default, 0), ^{                @synchronized (object)        {while            (YES) {                                [object Removemethod];}}}            );

using nsconditionlock Object

Nsconditionlock object defines a mutex that can be used to lock and unlock a specific value. Do not confuse this type of lock and condition (nscondition). Its behavior and conditions are somewhat similar, but their implementation is very different.


#define Has_data 1#define no_data 0        nsconditionlock* condlock = [[Nsconditionlock alloc] initwithcondition:no_data] ;        nsmutablearray* products = [[Nsmutablearray alloc]init];        Dispatch_async (Dispatch_get_global_queue (dispatch_queue_priority_default, 0), ^{while                (1)        {            [ Condlock lock];            [Products addobject:@ "product"];            [Condlock unlockwithcondition:has_data];                    }    });        Dispatch_async (Dispatch_get_global_queue (dispatch_queue_priority_default, 0), ^{while                (1)        {            [ Condlock Lockwhencondition:has_data];            [Products Removelastobject];            [Condlock unlockwithcondition: (Products.count = = 0?) No_data:has_data)];          }            );


question: The above consumers are polling data in the thread, this will consume a lot of CPU resources, if you can be told when there is data, no data when idle wait, then we can use the conditions to complete, there are two ways ( Use POSIX Conditions or Use the nscondition class ).

Use nscondition class

nscondition classes are provided and POSIX the same semantics, but it encapsulates the lock and conditional data structures inside a single object. The result is an object that you can use like a mutex, and then wait for a specific condition.

The consumer obtains the lock, takes the product, if does not have, then wait, then will release the lock, until the thread wakes it to consume the product;

Producers manufacture products, first of all to obtain locks, and then production, and then hair signal, so that can wake wait consumers


nsmutablearray* products = [[Nsmutablearray alloc]init];    nscondition* condition = [[Nscondition alloc] init];        Dispatch_async (Dispatch_get_global_queue (dispatch_queue_priority_default, 0), ^{//        Consumer while        (1)        {            [condition lock];                        while (Products.count <) {                [condition wait];            }            [Products removeobjectatindex:0];                        [Condition unlock];        }            });        Dispatch_async (Dispatch_get_global_queue (dispatch_queue_priority_default, 0), ^{//        producer while        (1)        {            [condition lock];                        [Products addobject:@ "product"];                        [Condition signal];                        [Condition unlock];                  }            });


-Refer to the Multithreaded Programming Guide


iOS thread sync and lock

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.