IOS thread-Safe @synchronized usage

Source: Internet
Author: User

usage of @synchronized (self):

The role of @synchronized is to create a mutex that ensures that no other thread modifies the self object at this time. This is a lock token for objective-c, which prevents the self object from being accessed by other threads at the same time, and acts as a thread protection.

For example: A cinema, with 3 conductors. The total number of movies is fixed. 3 ticket sales, to judge the right and wrong tickets.

#import "ViewController.h"@interfaceViewcontroller ()/** Conductor*/@property (nonatomic, strong) Nsthread*thread01;/** Conductor*/@property (nonatomic, strong) Nsthread*thread02;/** Ticket Clerk*/@property (nonatomic, strong) Nsthread*thread03;/** Total number of tickets*/@property (nonatomic, assign) Nsinteger Ticketcount;/** Lock Object*///@property (nonatomic, strong) NSObject *locker;@end@implementationViewcontroller- (void) viewdidload {[Super viewdidload]; //self.locker = [[NSObject alloc] init];Self.ticketcount= -; SELF.THREAD01= [[Nsthread alloc] initwithtarget:self selector: @selector (Saleticket)Object: nil]; Self.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";}- (void) Touchesbegan: (Nsset *) touches withevent: (Uievent *)Event{[self.thread01 start];    [SELF.THREAD02 start]; [Self.thread03 start];}- (void) saleticket{ while(1) {@synchronized (self) {//First Take out the totalNsinteger count =Self.ticketcount; if(Count >0) {Self.ticketcount= Count-1; NSLog (@"%@ sold a ticket and left%zd.", [Nsthread currentthread].name, Self.ticketcount); } Else{NSLog (@"The tickets are sold out.");  Break; }        }    }}@end

IOS thread-Safe @synchronized usage

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.