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:
8 9 #import "YYViewController.h" @interface Yyviewcontroller () 13//remaining votes @property (nonatomic,assign) int Le Ftticketscount;16 @property (nonatomic,strong) nsthread *thread1;17 @property (nonatomic,strong) Nsthread *thread2;18 @ Property (Nonatomic,strong) nsthread *thread3;19 @end22 @implementation YYViewController25-(void) Viewdid LOAD28 {[Super viewdidload];30 31//default 20 tickets] self.leftticketscount=10;34 35//Open multiple threads, simulate ticket sales 36 37 Self.thread1=[[nsthread alloc]initwithtarget:self selector: @selector (selltickets) object:nil];38 [Email pro Tected] "conductor a"; Self.thread2=[[nsthread alloc]initwithtarget:self selector: @selector (selltickets) Object:nil]; [email protected] "conductor B"; Self.thread3=[[nsthread alloc]initwithtarget:self selector: @selector (Sell Tickets) object:nil];46 [email protected] "conductor C";}48 (void) sellTickets51 {1) {53 1. First check the number of votes count=self Int.leftticketscount;55 if (count>0) {56//pause for a period of time [Nsthread sleepfortimeinterval:0.002];5 8 59//2. Votes -160 self.leftticketscount= count-1;61 62//Get current thread Nsthread * Current=[nsthread currentthread];64 NSLog (@ "%@--sold a ticket and%d tickets left", current,self.leftticketscount);}else 66 {67//exit thread [Nsthread exit];69}70}71}72-(void) Touchesbegan: (NSSe T *) touches withevent: (uievent *) event75 {76//open thread [Self.thread1 start];79 [self.thread2 start];80] [ Self.thread3 start];81}83 @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:
8 9 #import "YYViewController.h" @interface Yyviewcontroller () 12 13//remaining votes @property (nonatomic,assign) int LEFTT Icketscount;15 @property (nonatomic,strong) nsthread *thread1;16 @property (nonatomic,strong) Nsthread *thread2;17 @ Property (Nonatomic,strong) nsthread *thread3;18 @end19 @implementation YYViewController21-(void) ViewDidLoad23 { [Super VIEWDIDLOAD];25//default has 20 tickets self.leftticketscount=10;27//Open multiple threads, mock ticket sales self.thread1=[ [Nsthread alloc]initwithtarget:self selector: @selector (selltickets) object:nil];30 [email protected] "conductor a"; Self.thread2=[[nsthread alloc]initwithtarget:self selector: @selector (selltickets) object:nil];34 [EMAIL&N Bsp;protected] "conductor B"; Self.thread3=[[nsthread alloc]initwithtarget:self selector: @selector (selltickets) object : nil];38 [email protected] "conductor C";}41-(void) SellTickets44 {1) {@synchronized (self) {//Only add a lock 47//1. Check number of votes 48 49 int count=self.leftticketscount;50 if (count>0) {51//pause for a period of time [Nsthread Sleepfort imeinterval:0.002];53//2. Number of votes -154 self.leftticketscount= count-1;56//get current thread 57 Nsthread *current=[nsthread currentthread];58 NSLog (@ "%@--sold a ticket, and%d tickets remaining", Current,self.leftticketscount); }else61 {62//exit thread [Nsthread exit];64}65}66}67}68 (void) Touchesbegan: (Nsset *) touches withevent: (uievent *) event71 {72 73//Open thread [Self.thread1 start];75 [Self.thread2 start];76 [self.thread3 start];77}78 @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
1 @property (assign, atomic) int age;2 3-(void) Setage: (int) age4 {5 6 @synchronized (self) {7 _age = Age;8 } 9}
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