IOS thread security @ synchronized usage, ios @ synchronized
@ Synchronized (self) usage:
@ Synchronized creates a mutex lock to ensure that no other threads modify the self object at this time. This is a lock token of objective-c, which prevents self objects from being accessed by other threads at the same time and plays a thread protection role.
For example, a cinema has three conductor. The total number of movies is fixed. When the three ticket sellers sell tickets, they must judge whether there are no or no tickets.
# Import "ViewController. h "@ interface ViewController ()/** conductor 01 */@ property (nonatomic, strong) NSThread * thread01;/** conductor 02 */@ property (nonatomic, strong) NSThread * thread02;/** conductor 03 */@ property (nonatomic, strong) NSThread * thread03;/** total number of tickets */@ property (nonatomic, assign) NSInteger ticketCount; /** Lock Object * // @ property (nonatomic, strong) NSObject * locker; @ end @ implementation ViewController-(void) viewDidLoad {[super viewDidLoad]; // self. locker = [[NSObject alloc] init]; self. ticketCount = 100; self. thread01 = [[NSThread alloc] initWithTarget: self selector: @ selector (saleTicket) object: nil]; self. thread01.name = @ "conductor 01"; self. thread02 = [[NSThread alloc] initWithTarget: self selector: @ selector (saleTicket) object: nil]; self. thread02.name = @ "conductor 02"; self. thread03 = [[NSThread alloc] initWithTarget: self selector: @ selector (saleTicket) object: nil]; self. thread03.name = @ "conductor 03";}-(void) touchesBegan :( NSSet *) touches withEvent :( UIEvent *) event {[self. thread01 start]; [self. thread02 start]; [self. thread03 start];}-(void) saleTicket {while (1) {@ synchronized (self) {// retrieve the total number of NSInteger count = self. ticketCount; if (count> 0) {self. ticketCount = count-1; NSLog (@ "% @ sold a ticket, with % zd remaining", [NSThread currentThread]. name, self. ticketCount);} else {NSLog (@ "tickets sold out"); break ;}}}@ end