#import "ViewController.h" @interface ViewController () { nsinteger _ Cnt; nslock *_lock;} @end @implementation viewcontroller- (void) viewdidload { [super viewdidload]; //must first create a lock _lock = [[nslock alloc] init]; [nsthread detachnewthreadselector: @selector ( Thread1click) toTarget:self withObject:nil]; [NSThread Detachnewthreadselector: @selector (Thread2click) totarget:self withobject:nil];} /* the following two threads execute functions co-operate the same resource variable if we don't do any processing then two threads will scramble for resources so that we don't get the results we want, the data can lead to confusion //If two threads are going to operate on the same resource, then we generally need to lock up, lock when accessing resources, end of visit unlock */#pragma mark - A function called in a child Line//thread 1 want to do two times between execution between interval 10- (void) Thread1click{ nslog (@ "Thread 1 start"); //locking /* once thread execute [_lock lock], check first There is no lock, if the lock then when the front end will block until this lock unlock to continue to execute, if lock is not locked, immediately with lock lock continue to execute the following code multiple threads of the same resource must be the same lock //locking words to be careful to prevent deadlock */ [_lock lock]; for (nsinteger i = 0; i < 10; i++) { _cnt += 10; nslog (@ "%s_cnt:%ld", __func__,_cnt); [nsthread sleepfortimeinterval:0.5]; } [_lock unlock]; nslog (@ "Thread 1 is about to end");} Thread 2 wants the phenomenon is each interval 2- (void) THREAD2CLICK{&NBSP;&NBSP;&NBsp; nslog (@ "Thread 2 start"); [_lock lock]; for (nsinteger i = 0; i < 10; i++) { _cnt -= 2; nslog (@ "%s_ Cnt:%ld ", __func__,_cnt); [nsthread sleepfortimeinterval:0. 5]; } [_lock unlock]; nslog (@ "Thread 2 is about to end");} - (void) didreceivememorywarning { [super didreceivememorywarning]; // dispose of any resources that can be recreated.} @end
Simple example of the iOS thread lock