iOS development multithreaded article-thread safety
One, multi-threaded security risks
Resource sharing
1 of resources may be shared by multiple threads, that is, multiple threads may access the same block of resources
For example, multiple threads access the same object, the same variable, the same file
Data confusion and data security issues can easily arise when multiple threads access the same resource
Example one:
Example two:
Problem code:
////YYVIEWCONTROLLER.M//05-Thread Safety////Created by Apple on 14-6-23.//Copyright (c) 2014 itcase. All rights reserved.//#import"YYViewController.h"@interface Yyviewcontroller ()//number of votes left@property (nonatomic,assign)intLeftticketscount, @property (nonatomic,strong) Nsthread*Thread1, @property (nonatomic,strong) Nsthread*thread2, @property (nonatomic,strong) Nsthread*thread3, @end @implementation yyviewcontroller- (void) viewdidload{[Super Viewdidload]; //There are 20 tickets by defaultSelf.leftticketscount=Ten; //open multiple threads and simulate ticket salesSelf.thread1=[[nsthread alloc]initwithtarget:self selector: @selector (selltickets)Object: nil]; Self.thread1.name=@"Conductor a"; Self.thread2=[[nsthread alloc]initwithtarget:self selector: @selector (selltickets)Object: nil]; Self.thread2.name=@"Conductor B"; Self.thread3=[[nsthread alloc]initwithtarget:self selector: @selector (selltickets)Object: nil]; Self.thread3.name=@"Conductor C";} -(void) selltickets{ while(1) { //1. Check the number of votes first intCount=Self.leftticketscount; if(count>0) { //pause for some time[Nsthread Sleepfortimeinterval:0.002]; //2. Number of votes -1Self.leftticketscount= count-1; //gets the current threadNsthread *current=[Nsthread CurrentThread]; NSLog (@"%@--sold a ticket and%d tickets left.", Current,self.leftticketscount); }Else { //Exit Thread[Nsthread exit]; } }}-(void) Touchesbegan: (Nsset *) touches withevent: (Uievent *)Event{ //Open Thread[Self.thread1 start]; [Self.thread2 start]; [Self.thread3 start];} @end
Printing results:
Second, the security hidden trouble analysis
Third, how to solve
Mutex use format
@synchronized (Lock Object) {//code to be locked}
Note: locking 1 parts of code with only 1 locks, with multiple locks is not valid
code example:
////YYVIEWCONTROLLER.M//05-Thread Safety////Created by Apple on 14-6-23.//Copyright (c) 2014 itcase. All rights reserved.//#import"YYViewController.h"@interface Yyviewcontroller ()//number of votes left@property (nonatomic,assign)intLeftticketscount, @property (nonatomic,strong) Nsthread*Thread1, @property (nonatomic,strong) Nsthread*thread2, @property (nonatomic,strong) Nsthread*thread3, @end @implementation yyviewcontroller- (void) viewdidload{[Super Viewdidload]; //There are 20 tickets by defaultSelf.leftticketscount=Ten; //open multiple threads and simulate ticket salesSelf.thread1=[[nsthread alloc]initwithtarget:self selector: @selector (selltickets)Object: nil]; Self.thread1.name=@"Conductor a"; Self.thread2=[[nsthread alloc]initwithtarget:self selector: @selector (selltickets)Object: nil]; Self.thread2.name=@"Conductor B"; Self.thread3=[[nsthread alloc]initwithtarget:self selector: @selector (selltickets)Object: nil]; Self.thread3.name=@"Conductor C";}-(void) selltickets{ while(1) {@synchronized (self) {//only one lock can be added .//1. Check the number of votes first intCount=Self.leftticketscount; if(count>0) { //pause for some time[Nsthread Sleepfortimeinterval:0.002]; //2. Number of votes -1Self.leftticketscount= count-1; //gets the current threadNsthread *current=[Nsthread CurrentThread]; NSLog (@"%@--sold a ticket and%d tickets left.", Current,self.leftticketscount); }Else { //Exit Thread[Nsthread exit]; } } }}-(void) Touchesbegan: (Nsset *) touches withevent: (Uievent *)Event{ //Open Thread[Self.thread1 start]; [Self.thread2 start]; [Self.thread3 start];} @end
Perform
Advantages and disadvantages of mutual exclusion lock
Advantages: It can effectively prevent the data security problem caused by multi-thread snatch resource
Cons: Consumes a lot of CPU resources
Use of mutexes: Multiple threads rob the same piece of resources
Related jargon: thread synchronization , multiple threads performing tasks sequentially
Mutex is the use of thread synchronization technology
IV: Atomic and non-atomic properties
OC has nonatomic and atomic two choices when defining attributes
Atomic: Atomic attribute, locking for setter method (default is Atomic)
Nonatomic: Non-atomic attribute, does not lock the setter method
Atomic Plus Lock principle
int Age ; -(void) Setage: (int) age{ @synchronized (self) { = age ; }}
Selection of atomic and non-atomic properties
Comparison of Nonatomic and atomic
Atomic: Thread-safe, requires a lot of resources
nonatomic: Non-thread-safe, suitable for small memory mobile devices
Recommendations for iOS development
All properties are declared as Nonatomic
Try to avoid multiple threads robbing the same piece of resources
As far as possible to locking, resource-grabbing business logic to the server-side processing, reduce the pressure of mobile clients
iOS development multithreaded article-thread safety