ios--multithreaded Applications

Source: Internet
Author: User

I. Shared resources

Shared resources: An in-memory resource that is accessed by multiple processes at the same time, and each process may modify the data for that resource

Problem: If thread a accesses a block of resource C and modifies the data in it, thread B also accesses resource C and modifies the data in C, so that when thread A and thread B are finished, the data in resource C is not initially set.

At this point, if the user wants to get the data of resource C modified by thread A, but the data of resource C is also modified by thread B, the data obtained is wrong, and if the user wants to get the data of resource C modified by thread B, but the data of resource C is also modified by thread A, the wrong data is obtained.

See the code below to sell train tickets for example

Set up train ticket data model

1 //LHTicketModal.h2 #import<Foundation/Foundation.h>3 4 @interfaceLhticketmodal:nsobject5 6@property (nonatomic) Nsuinteger Ticketcount;//number of votes left7@property (nonatomic) Nsuinteger Ticketsalecount;//Quantity Sold8 9 @endTen  One //LHTICKETMODAL.M A #import "LHTicketModal.h" -  - Static ConstNsuinteger Ktickettotalcount = -; the  - @implementationLhticketmodal -  --(instancetype) init { +  -Self =[Super init]; +      A     if(self) { at      -         //the number of votes left to initialize should be the total number -_ticketcount =Ktickettotalcount; -          -         //Initialize the number of sell votes should be 0 -_ticketsalecount =0; in      -     } to      +     returnSelf ; -  the } *  $ @end

Uiviewcontroller Code

1 //LHSharedViewController.h2 #import "LHSharedViewController.h"3 #import "LHTicketModal.h"4 5 @interfaceLhsharedviewcontroller ()6 7 //Ticket Model8@property (nonatomic, strong) Lhticketmodal *ticket;9 Ten //Thread Object One@property (nonatomic, strong) Nsthread *THREADBJ; A@property (nonatomic, strong) Nsthread *threadsh; -  - @end the  - //LHSHAREDVIEWCONTROLLER.M - @implementationLhsharedviewcontroller -  +- (void) Viewdidload { -      + [Super Viewdidload]; A      at     //1. Initialize the number of votes model object -_ticket =[[Lhticketmodal alloc] init]; -      -     //2. Initialize the thread object and set the name of the thread -_THREADBJ = [[Nsthread alloc] initwithtarget:self selector: @selector (selltickets:)Object:@"Beijing Sell"]; -      in_threadbj.name =@"Beijing"; -      to_THREADSH = [[Nsthread alloc] initwithtarget:self selector: @selector (selltickets:)Object:@"Shanghai Sell"]; +      -_threadsh.name =@"Shanghai"; the  * } $ Panax Notoginseng //methods for thread execution -- (void) Selltickets: (NSString *) str { the  +      while(YES) { A      the         //determine whether the remaining amount is greater than 0, greater than 0 can be sold +         if(_ticket.ticketcount >0) { -          $             //pause for some time $[Nsthread Sleepfortimeinterval:0.2]; -              -             //sell a ticket, the remaining number of votes minus 1, the number of sell votes plus 1 the_ticket.ticketcount--; -             Wuyi_ticket.ticketsalecount++; the              -             //Get current Process WuNsthread * CurrentThread =[Nsthread CurrentThread]; -              AboutNSLog (@"%@ sold a ticket, and%lu tickets left.", Currentthread.name, _ticket.ticketcount); $              -         } -      -     } A  + } the  - //action method of the button $-(Ibaction) Startsalebtnclick: (ID) Sender { the      the     //Open Thread the [_THREADBJ start]; the      - [_threadsh start]; in      the      the}

When the button is clicked, the thread starts to run, and the result

As you can see, shared resources are accessed and modified by multiple threads, causing the user to get the wrong data

Then the solution to this situation is to lock

Locking refers to a piece of code to lock, lock, if a thread is already in the data of the shared resource modification, there will be no other threads to access the resource for modification, until the current thread has finished modifying the resource's code, other processes can modify it

The shared resources can be regarded as a room, the thread to see a man; When a person enters a room, they lock the door (locking) and decorate the room, at which time others are not able to enter, because there is no key; until the current people out of the room, other people can enter the room to decorate

There are many ways to lock, and here are two

Method One: Use @synchronized (Lock object) {} keyword

Just modify the Selltickets method of the above code, the rest is unchanged, here the method name is changed to SELLTICKETS_V2

1- (void) SELLTICKETS_V2: (NSString *) str {2     3      while(YES) {4         5         //Lock the current object6 @synchronized (self) {7             8             //determine whether the remaining amount is greater than 0, greater than 0 can be sold9             if(_ticket.ticketcount >0) {Ten              One                 //pause for some time A[Nsthread Sleepfortimeinterval:0.2]; -              -                 //sell a ticket, the remaining number of votes minus 1, the number of sell votes plus 1 the_ticket.ticketcount--; -              -_ticket.ticketsalecount++; -              +                 //Get current Process -Nsthread * CurrentThread =[Nsthread CurrentThread]; +              ANSLog (@"%@ sold a ticket, and%lu tickets left.", Currentthread.name, _ticket.ticketcount); at              -             } -              -         } -          -     } in      -}

Run the program again and click the button. Results

Mode two: Using the Nscondition class

Declared in the class extension and initialized in the Viewdidload method

1- (void) Selltickets_v3: (NSString *) str {2     3      while(YES) {4         5         //using nscondition locking6[_ticketconditionLock];7         8         //determine whether the remaining amount is greater than 0, greater than 0 can be sold9         if(_ticket.ticketcount >0) {Ten                  One             //pause for some time A[Nsthread Sleepfortimeinterval:0.2]; -                  -             //sell a ticket, the remaining number of votes minus 1, the number of sell votes plus 1 the_ticket.ticketcount--; -                  -_ticket.ticketsalecount++; -                  +             //Get current Process -Nsthread * CurrentThread =[Nsthread CurrentThread]; +                  ANSLog (@"%@ sold a ticket, and%lu tickets left.", Currentthread.name, _ticket.ticketcount); at              -         } -          -         //unlock with nscondition - [_ticketcondition unlock]; -          in     } -      to}

The result is the same as above

When using nscondition, place the locked code in the middle of LOAC and unlock

Summarize:

1. Advantages and disadvantages of mutual exclusion lock

Advantages: Effectively prevent data security problems caused by multi-thread snatch resources

Cons: Consumes a lot of CPU resources

2. The premise of the use of mutual exclusion lock

Multiple threads rob the same resource

Thread synchronization, mutex is the use of thread synchronization

ios--multithreaded Applications

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.