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:
1//2//YYVIEWCONTROLLER.M 3//05-Thread Safety 4//5//Created by Apple on 14-6-23. 6//Copyright (c) 2014 itcase. All rights reserved. 7//8 9 #import "YYViewController.h" @interface Yyviewcontroller () 13//remaining votes @property (Nonatomic,assign) in T leftticketscount;16 @property (nonatomic,strong) nsthread *thread1;17 @property (nonatomic,strong) Nsthread *thread2; @property (Nonatomic,strong) nsthread *thread3;19 @end22 @implementation YYViewController25-(void) Vie WDIDLOAD28 {[Super viewdidload];30 31//default 20 tickets] self.leftticketscount=10;34 35//Open multiple threads, simulate ticket sales 36 PNS self.thread1=[[nsthread alloc]initwithtarget:self selector: @selector (selltickets) object:nil];38 [email  ;p rotected] "conductor a"; Self.thread2=[[nsthread alloc]initwithtarget:self selector: @selector (selltickets) object: nil];42 [email protected] "conductor B"; Self.thread3=[[nsthread alloc]initwithtarget:self selector: @selector (selltickets) Object:nil];46 [email protected] "conductor C";}48-(void) SellTickets51 {1) {53//1. Check the number of votes first 54 int count=self.leftticketscount;55 if (count>0) {56//pause for a period of time [Nsthread SLEEPFO rtimeinterval:0.002];58 59//2. Votes -160 self.leftticketscount= count-1;61 62//Get current thread 63 Nsthread *current=[nsthread currentthread];64 NSLog (@ "%@--sold a ticket and%d tickets left", CURRENT,SELF.LEFTTICKETSC Ount)}else66 {67//exit thread [Nsthread exit];69}70}71}72-(v OID) Touchesbegan: (Nsset *) touches withevent: (uievent *) event75 {76//open thread [Self.thread1 start];79] Hread2 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:
1//2//YYVIEWCONTROLLER.M 3//05-Thread Safety 4//5//Created by Apple on 14-6-23. 6//Copyright (c) 2014 itcase. All rights reserved. 7//8 9 #import "YYViewController.h" @interface Yyviewcontroller () 12 13//remaining votes @property (nonatomic,assign) int L Eftticketscount;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) {//can only add a lock 47 1. Check the number of votes first (count=self.leftticketscount;50 int) if (count>0) {51//pause for a period of 52 [Nsthread sleepfortimeinterval:0.002];53//2. Votes -154 self.leftticketscount= count-1;56 Get current thread Nsthread *current=[nsthread currentthread];58 NSLog (@ "%@--sold a ticket and%d tickets left", Current,s Elf.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 Multithreading Chapter 03-Thread Safety