One, multi-threading in iOS
- Multithreading principle (before multithreading this piece did not learn, before the understanding of multithreading is also wrong, here to correct, study this piece)
- There are several ways to implement multi-threading in iOS:
Second, Nsthread threading class simple and practical (directly on the code)
Three, multi-threaded security hidden trouble
-
- 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
- When multiple threads access the same piece of resources, it is easy to trigger data confusion and data security issues (example of saving money, multiple ticket sales)
- Ways to resolve security risks---mutex (plot)
- A simple introduction to mutual exclusion locks
- Code implementation of the example of ticket seller
1 #import "ViewController.h"2 3 @interfaceViewcontroller ()4 /** THREAD01*/5@property (nonatomic,strong) Nsthread *thread01;6 /** THREAD02*/7@property (nonatomic,strong) Nsthread *thread02;8 /** THREAD03*/9@property (nonatomic,strong) Nsthread *thread03;Ten /** Ticketcount*/ One @property (nonatomic,assign) Nsinteger ticketcount; A @end - - @implementationViewcontroller the -- (void) Viewdidload { - [Super Viewdidload]; - +Self.ticketcount = -; - + //thread creation does not execute after start the curly braces are destroyed, so the member variables are stored here. ASELF.THREAD01 = [[Nsthread alloc] initwithtarget:self selector: @selector (Saleticket)Object: nil]; atSelf.thread01.name =@"Conductor"; -SELF.THREAD02 = [[Nsthread alloc] initwithtarget:self selector: @selector (Saleticket)Object: nil]; -Self.thread02.name =@"Conductor"; -SELF.THREAD03 = [[Nsthread alloc] initwithtarget:self selector: @selector (Saleticket)Object: nil]; -Self.thread03.name =@"Conductor"; - } in -- (void) Touchesbegan: (Nsset<uitouch *> *) touches withevent: (Uievent *)Event { to + [self.thread01 start]; - [self.thread02 start]; the [self.thread03 start]; * $ }Panax Notoginseng -- (void) Saleticket the { +@synchronized (self) {//add a mutex, any object in parentheses can be, but must be the same! A the while(1) { + //total number of remaining votes removed -Nsinteger count =Self.ticketcount; $ if(Count >0) { $Self.ticketcount = count-1; -NSLog (@"%@ sold his ticket and%ld left.", [Nsthread currentthread].name,self.ticketcount); -}Else { the -NSLog (@"%@ sold out the tickets .", [Nsthread currentthread].name);Wuyi Break; the } - Wu } - } About } $ - @end
- Result of printing without mutex lock
Iv. Atomic and non-atomic properties--atomic, Nonatomic
V. Communication between threads (exercise: An exercise to download pictures)
iOS Edge Learning-multithreading, nsthread, thread safety, and communication between threads