dyfviewcontroller.m//623-05-Thread synchronization issues////Created by DYF on 14-6-23.//Copyright (c) 2014 ___fullusername___. All rights reserved.//#import "DYFViewController.h" @interface Dyfviewcontroller () @property (nonatomic, assign) int Leftcount, @property (nonatomic, strong) Nsthread *thread0; @property (nonatomic, strong) Nsthread *thread1; @property ( Nonatomic, strong) Nsthread *thread2; @end @implementation dyfviewcontroller-(void) viewdidload{[Super viewDidLoad];// Additional setup after loading the view, typically from a nib. The default is 100 self.leftcount = 100; Open multiple threads at the same time sell ticket self.thread0 = [[Nsthread alloc] initwithtarget:self selector: @selector (saleticket) object:@ "000"]; Self.thread0.name = @ "0000"; Priority Self.thread0.threadPriority = 1.0; Self.thread1 = [[Nsthread alloc] initwithtarget:self selector: @selector (saleticket) object:@ "000"]; Self.thread1.name = @ "1111"; self.thread1.threadPriority = 0.0; Self.thread2 = [[Nsthread alloc]Initwithtarget:self selector: @selector (saleticket) object:@ "000"]; Self.thread2.name = @ "2222"; self.thread2.threadPriority = 0.0; }/** * Sell ticket */-(void) saleticket{//nslock *lock = [[Nslock alloc] init];//lock.trylock//Lock.lock while (1) {@synchronized (self) {//Start yoke//1. First check the number of votes int count = [self leftcount]; if (Count > 0) {//votes-1 [Self Setleftcount: (count-1)]; suspension [Nsthread sleepfortimeinterval:0.0004]; Nsthread *currentt = [Nsthread CurrentThread]; NSLog (@ "%@,-------%d", Currentt.name, Self.leftcount); }else {//exit thread [Nsthread exit]; }}//Unlock}}-(void) Touchesbegan: (Nsset *) touches withevent: (uievent *) event{[self.thread0 start]; [Self.thread1 start]; [Self.thread2 start];} @end
Summary:
--------------Thread Security issues (multithreading security implications)-------
1. Resource Sharing
• A resource may be shared by multiple threads, that is, multiple threads may access the same piece of resources
• For example, multiple threads access the same object, the same variable, the same file
2. When multiple threads access the same resource, data confusion and data security issues can easily arise
3. Example
eg 1 Save money
eg 2 Selling tickets
-----------------security vulnerability Resolution-Mutex lock-----
1. Format
@synchronized (Lock Object)
{//code that needs to be locked
}
Note: Locking a copy of the code can only be used with 1 locks, which is not valid with multiple locks
2. Pros and cons
• Advantages: Can effectively prevent multi-threaded snatch resources caused by security problems
• Cons: Consumes a lot of CPU resources
3. Use of mutexes: Multiple threads rob the same piece of resources
4. Related terms: Thread synchronization
means: Multiple threads perform tasks sequentially
• Mutex is the use of thread synchronization technology