Method One, @synchronized (ID anobject), (the simplest method)
Automatically locks the parameter objects to ensure code thread safety within the critical area
1 @synthesize (self) 2 {3 // This code is mutually exclusive to other @synthesize (self) 4 5 //self points to thesame object 6 }
Method Two, Nslock
The Nslock object implements the Nslocking protocol, which contains several methods:
Lock, plus lock
Unlock, unlocking
Trylock, attempts to lock, if failed, does not block the thread, will immediately return no
Lockbeforedate:, temporarily blocks the thread before the specified date (if no lock is acquired), if the lock is not acquired at maturity, the thread is awakened, and the function immediately returns no
1 Nslock *thislock = [[Nslock alloc] init]; 2 if Lock ] {3 4 // Add the code you need here to 5 6 [thislock unlock]; 7 8 }
Method Three, Nsrecursivelock, recursive lock
Nsrecursivelock, multiple calls do not block the thread that has acquired the lock.
1Nsrecursivelock *thelock =[[Nsrecursivelock alloc] init];2 voidMyFunction (intvalue)3 {4[ThelockLock];5 if(Value! =0)6<span style=@"font-size:14px"></span>{7-value;8 myFunction (value);9 }Ten One [Thelock unlock]; A } - -MyFunction (5) ;
Method Four, Nsdistributedlock, distribution lock
Nsdistributedlock, distributed lock, file way implementation, can cross-process
Use the Trylock method to obtain the lock.
Use the Unlock method to release the lock.
If a process that acquires a lock is hung before releasing the lock, the lock will not be released until the lock can be forcibly acquired through Breaklock.
Method Five, Nsconditionlock, conditional lock
Nsconditionlock, conditional lock, can set conditions
1 //Public Part2 IDConditionlock =[[Nsconditionlock alloc] initwithcondition:no_data];3 //Line Cheng, producer4 while(true) {5 [Conditionlock Lockwhencondition:no_data];6 //Production Data7 [Conditionlock Unlockwithcondition:pro_data];8 }9 Ten //thread two, consumer One while(true) { A - [Conditionlock Lockwhencondition:pro_data]; - //Consumer the [Conditionlock Unlockwithcondition:no_data]; -}
IOS multi-line lock mutex synchronization