当前位置:网站首页>IOS development - multithreading - thread safety (3)
IOS development - multithreading - thread safety (3)
2022-06-24 02:39:00 【PGzxc】
IOS Development of —— Multithreading - Thread safety (3)
One Multithreading resource sharing
- 1 Block resources may be shared by multiple threads , That is to say Multiple threads may access the same resource
- For example, multiple threads access the same object 、 The same variable 、 The same file
- When multiple threads access the same block of resources , It's easy to trigger Data disorder and data security problem
Two Examples of safety hazards
2.1 Example 1 saving and withdrawing money

2.2 Selling tickets

3、 ... and Multi thread ticket selling
3.1 explain
- After the program starts , Turn on 1,2,3 Three threads sell tickets
- Three threads are sold together 100 Tickets
3.2 Code
#import "ViewController.h"
@interface ViewController ()
@property(nonatomic,strong) NSThread *thread1;
@property(nonatomic,strong) NSThread *thread2;
@property(nonatomic,strong) NSThread *thread3;
@property(nonatomic,assign) int leftTicketCount;// The number of votes left
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.leftTicketCount=100;
self.thread1=[[NSThread alloc]initWithTarget:self selector:@selector(saleTicket) object:nil];
[email protected]"1 Window No ";
self.thread2=[[NSThread alloc]initWithTarget:self selector:@selector(saleTicket) object:nil];
[email protected]"2 Window No ";
self.thread3=[[NSThread alloc]initWithTarget:self selector:@selector(saleTicket) object:nil];
[email protected]"3 Window No ";
self.locker=[[NSObject alloc]init];
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
[self.thread1 start];
[self.thread2 start];
[self.thread3 start];
}
// Selling tickets
-(void)saleTicket
{
while (1) {
int count=self.leftTicketCount;
if (count>0) {
[NSThread sleepForTimeInterval:0.1];
self.leftTicketCount=count-1;
NSLog(@"%@ Sold a ticket , The remaining %d Tickets ",[NSThread currentThread].name,count);
}else{
return;// Get out of the loop
}
}
}
@end
3.3 The phenomenon
2022-02-20 23:10:18.593201+0800 05- Thread safety problem [45790:535673] 3 Window number sold a ticket , The remaining 2 Tickets
2022-02-20 23:10:18.593201+0800 05- Thread safety problem [45790:535672] 2 Window number sold a ticket , The remaining 2 Tickets
2022-02-20 23:10:18.593201+0800 05- Thread safety problem [45790:535671] 1 Window number sold a ticket , The remaining 2 Tickets
2022-02-20 23:10:18.696806+0800 05- Thread safety problem [45790:535671] 1 Window number sold a ticket , The remaining 1 Tickets
2022-02-20 23:10:18.696809+0800 05- Thread safety problem [45790:535672] 2 Window number sold a ticket , The remaining 1 Tickets
2022-02-20 23:10:18.696806+0800 05- Thread safety problem [45790:535673] 3 Window number sold a ticket , The remaining 1 Tickets
3.4 Safety hazard analysis

3.5 Security risks are solved ( The mutex )

Four The mutex
4.1 Mutex usage format
@synchronized( Lock object ){// Code that needs to be locked
Be careful : lock 1 Code only 1 The lock , It is invalid to use more than one lock
}
4.2 Advantages and disadvantages of mutex
- advantage : It can effectively prevent data security problems caused by multithreading
- shortcoming : It takes a lot of CPU resources
4.3 The premise of using mutex
Multiple threads scramble for the same resource
4.4 Related technical terms : Thread synchronization
- Thread synchronization means : Multiple threads execute on the same line ( Perform tasks in sequence )
- The mutex : Is the use of thread synchronization technology
4.5 Atomic and non atomic properties
- OC When defining properties, there are nonatomic and atomic Two options
- Atomic: Thread safety , It takes a lot of resources
- Nonatomic: Non-thread safety , Suitable for small memory mobile devices
3.5 iOS Suggestions for development
- All properties are declared as nonatomic
- Try to avoid multiple threads seizing the same resource
- Try to lock 、 The business logic of resource grabbing is handed over to the server for processing , Reduce the pressure on mobile clients
5、 ... and Code after locking
-(void)saleTicket
{
while (1) {
@synchronized(self) {
int count=self.leftTicketCount;
if (count>0) {
[NSThread sleepForTimeInterval:0.1];
self.leftTicketCount=count-1;
NSLog(@"%@ Sold a ticket , The remaining %d Tickets ",[NSThread currentThread].name,count);
}else{
return;// Get out of the loop
}
}
}
}
边栏推荐
- How to build an enterprise website? Is it difficult?
- [supply chain • case] Tianneng group: the key to understanding the leading battery manufacturer to achieve the first profit fault
- How does [lightweight application server] build a cross-border e-commerce management environment?
- How to view the speech synthesis platform how to use the speech synthesis platform
- What is ITF barcode
- Gin framework: add Prometheus monitoring
- Operation and maintenance platform tcapulusdb transaction management
- Face recognition using cidetector
- Using the database middleware MYCAT to realize read-write separation (dual master and dual slave)
- IP address and subnet partition are very important. This article is very fragrant!
猜你喜欢
随机推荐
Pan micro reached cooperation with Tencent to help enterprises connect with banking services and support enterprise digital upgrading
An attempt to use Navicat tool to copy and export MySQL database data
NFT metauniverse and the relationship between Games Golden Finance
Operation and maintenance platform tcapulusdb transaction management
How about Tencent cloud game server? Can the cloud game server play games
Which is a good human voice synthesis platform? What are the human voice synthesis application scenarios
What is a private VLAN? Eight part essay with pictures and texts.
[supply chain • case] Tianneng group: the key to understanding the leading battery manufacturer to achieve the first profit fault
Activiti obtains the initiator based on the process instance ID
Tke single node risk avoidance
Uipickerview show and hide animation
How to recover the garbled words in the software?
Are cloud game servers expensive to rent? Factors to consider in cloud game server leasing
Solution to session problem of missing laravel jump page
Crawler series: using API
Start tcapulusdb process
What is the backbone of marketing website construction? What does it do?
How to change the cloud desktop domain server password if you forget it?
What is data matrix code
Is a trademark domain name useful? How long does it take to register a domain name?


