<span id="Label3"></p><p><p><span style="color: #ff6600;">Categories of locks</span> : mutexes, recursive locks, conditional locks, spin locks, etc.</p></p><p><p><span style="color: #ff6600;">the implementation of the lock</span> : nslock,nsrecursivelock, nsconditionlock, @synchronized, GCD signal volume, etc.</p></p><p><p>Here are some common types of locks:</p></p><p><p><span style="color: #ff6600;">[email protected]: <span style="color: #000000;">Object level, mutex, Poor performance</span> deprecated</span></p></p><p style="margin-left: 30px;"><p style="margin-left: 30px;">@synchronized (add an OC object here, usually using Self) {</p></p><p style="margin-left: 30px;"><p style="margin-left: 30px;">Write the code to be locked Here.</p></p><p style="margin-left: 30px;"><p style="margin-left: 30px;">}</p></p><p><p><span style="color: #ff6600;"> <span style="color: #000000;">@synchronized Use note points</span></span></p></p><p><p><span style="color: #ff6600;"><span style="color: #000000;">1. Lock the code as little as possible</span></span></p></p><p><p><span style="color: #ff6600;"><span style="color: #000000;">2. The OC object to be added must be the same object in multiple threads, with a counter example</span></span></p></p><pre class="brush:objc;gutter:true;"><pre class="brush:objc;gutter:true;">-(void) viewdidload { [super viewdidload]; The number of tickets set is 5 _tickets = 5; Thread one nsthread *threadone = [[nsthread alloc] initwithtarget:self selector: @selector (saletickets) object:nil]; Threadone.name = @ "threadone"; Thread two nsthread *threadtwo = [[nsthread alloc] initwithtarget:self selector: @selector (saletickets) object:nil]; Open thread [threadone start]; [threadtwo start]; }-(void) saletickets{ nsobject *object = [[nsobject alloc] init]; While (1) { @synchronized (object) { [nsthread sleepfortimeinterval:1]; If (_tickets > 0) { _tickets--; NSLog (@ "number of votes left =%ld", _tickets); } else { NSLog (@ "ticket sold out"); break;}}}} </pre></pre><p><p>The result is that the ticket is wrong again, and the problem with this is that each thread creates an object, and the object behind the lock is different in different threads;</p></p><p><p></p></p><p><p>Change @synchronized (object) to @synchronized (self) to get the right result</p></p><p><p></p></p><p><p><span style="color: #ff6600;">2.NSLock: <span style="color: #000000;">Mutual Exclusion lock,</span></span></p></p><pre class="brush:objc;gutter:true;"><pre class="brush:objc;gutter:true;"> @interface viewcontroller () {nslock *mutexlock;} @property (assign, nonatomic) nsinteger tickets; @end @implementation viewcontroller-(void) viewdidload {[super viewdidl oad]; Create lock Mutexlock = [[nslock alloc] init]; The number of tickets set is 5 _tickets = 5; Thread one nsthread *threadone = [[nsthread alloc] initwithtarget:self selector: @selector (saletickets) object:nil]; Threadone.name = @ "threadone"; Thread two Nsthread *threadtwo = [[nsthread alloc] initwithtarget:self selector: @selector (saletickets) object:nil]; Open Thread [threadone start]; [threadtwo start]; }-(void) saletickets{while (1) {[nsthread sleepfortimeinterval:1]; Add Lock [mutexlock lock]; If (_tickets > 0) {_tickets--; NSLog (@ "number of votes left =%ld", _tickets); } else {NSLog (@ "ticket sold out"); Break }//unlock [mutexlock unlock]; }}</pre></pre><p><p>Nslock: using caution, The Lock method cannot be called multiple times, causing a deadlock</p></p><p><p></p></p><p><p><span style="color: #ff6600;">3.NSRecursiveLock: <span style="color: #000000;">Recursive lock</span></span></p></p><pre class="brush:objc;gutter:true;">@interface Viewcontroller () {nsrecursivelock *rslock;} @property (assign, nonatomic) nsinteger tickets; @end @implementation viewcontroller-(void) viewdidload {[super viewdidl oad]; Create lock recursive lock Rslock = [[nsrecursivelock alloc] init]; The number of tickets set is 5 _tickets = 5; Thread one nsthread *threadone = [[nsthread alloc] initwithtarget:self selector: @selector (saletickets) object:nil]; Threadone.name = @ "threadone"; Thread two Nsthread *threadtwo = [[nsthread alloc] initwithtarget:self selector: @selector (saletickets) object:nil]; Open Thread [threadone start]; [threadtwo start]; }-(void) saletickets{while (1) {[nsthread sleepfortimeinterval:1]; lock, the recursive lock can be added multiple times lock [rslock lock]; [rslock lock]; If (_tickets > 0) {_tickets--; NSLog (@ "number of votes left =%ld", _tickets); } else {NSLog (@ "ticket sold out"); Break }//unlock, only the corresponding number of times to unlock, other threads to Access. [rslock unlock]; [rsLOck unlock]; } }</pre><p><p></p></p><p><p><span style="color: #ff6600;">4.NSConditionLock: <span style="color: #000000;">Conditional Lock</span></span></p></p><p><p></p></p><p style="margin-left: 60px;"><p style="margin-left: 60px;"><span style="color: #008000;">Nsconditionlock: conditional lock, One thread gets the lock, other threads wait.</span></p></p><p style="margin-left: 60px;"><p style="margin-left: 60px;"></p></p><p style="margin-left: 60px;"><p style="margin-left: 60px;"><span style="color: #008000;">[xxxx lock]; Indicates that XXX expects to acquire a lock if no other thread obtains the lock (no need to judge the internal Condition) that it can execute this line of code, if there are already other threads that have acquired the lock (possibly a conditional lock, or an unconditional lock), wait until the other line threads unlocked</span></p></p><p style="margin-left: 60px;"><p style="margin-left: 60px;"></p></p><p style="margin-left: 60px;"><p style="margin-left: 60px;"><span style="color: #008000;">[xxx lockwhencondition:a conditions]; Indicates that if no other thread obtains the lock, but the condition inside the lock is not equal to the a condition, it still cannot get the lock and still waits. If the internal condition equals a condition, and no other thread obtains the lock, it enters the code area and sets it to obtain the lock, and any other thread waits for its code to complete until it is Unlocked.</span></p></p><p style="margin-left: 60px;"><p style="margin-left: 60px;"></p></p><p style="margin-left: 60px;"><p style="margin-left: 60px;"><span style="color: #008000;">[xxx unlockwithcondition:a conditions]; Represents the release lock, while the internal condition is set to a condition</span></p></p><p><p></p></p><pre class="brush:objc;gutter:true;"><pre class="brush:objc;gutter:true;">@interface viewcontroller () { nsconditionlock *_cdtlock;//conditional lock} @end @implementation viewcontroller-(void) Viewdidload { [super viewdidload]; Create conditional lock _cdtlock = [[nsconditionlock alloc] init]; [nsthread detachnewthreadselector: @selector (conditionLockAction1) totarget:self withobject:nil]; [nsthread detachnewthreadselector: @selector (conditionLockAction2) totarget:self withobject:nil]; } -(void) conditionLockAction1 { //blocking thread 2s [nsthread sleepfortimeinterval:2]; for (nsinteger i = 0; i < 3; i++) { //locking [_cdtlock lock]; NSLog (@ "i =%li", i); Release the lock and set the value of the condition property to I [_cdtlock unlockwithcondition:i];} } -(void) ConditionLockAction2 { //when The code snippet is identified as 2 o'clock synchronized, the current thread is blocked if it is identified as a different number. [_cdtlock lockwhencondition:2]; NSLog (@ "thread2"); [_cdtlock unlock]; }</pre></pre><p><p>Printing results:</p></p><p><p>If we replace [_cdtlock lockwhencondition:2] in the code with [_cdtlock lockwhencondition:1] we will find the following results</p></p><p><p>And what we expected after I = 1 printing thread2 not conform, This is because the code snippet in the ConditionLockAction1 also need to obtain a lock, while the loop is executed after the condition is placed into 2, Then ConditionLockAction2 will never have a chance to lock, so do not print thread2.</p></p><p><p>We can verify this by following the code</p></p><pre class="brush:objc;gutter:true;">@interface viewcontroller () {nsconditionlock *_cdtlock;//conditional lock} @end @implementation viewcontroller-(void) Viewdidloa D {[super viewdidload]; Create conditional lock _cdtlock = [[nsconditionlock alloc] init]; [nsthread detachnewthreadselector: @selector (conditionLockAction1) totarget:self withobject:nil]; [nsthread detachnewthreadselector: @selector (conditionLockAction2) totarget:self withobject:nil]; }-(void) conditionLockAction1 {//block thread 2s [nsthread sleepfortimeinterval:2]; for (nsinteger i = 0; i < 3; i++) {//locking [_cdtlock lock]; NSLog (@ "i =%li", i); Release the lock and set the value of the condition property to I [_cdtlock unlockwithcondition:i];<span style="color: #ff0000;"><span style="color: #ff0000;">//at The time I is 1 block thread 1s if (i = = 1) {[nsthread sleepfortimeinterval:1]; }</span></span>}}-(void) ConditionLockAction2 {//when The code snippet is identified as 2 o'clock synchronous, the current thread is blocked if it is identified as a different number. [_cdtlock lockwhencondition:1]; NSLog (@ "thread2"); [_cdtlock unlock]; }</pre><p><p>The result is the same as we expected it to Be.</p></p><p><p></p></p><p><p></p></p><p><p><span style="color: #ff6600;">5.NSCondition: <span style="color: #000000;">can be understood as a combination of mutexes and conditional locks</span></span></p></p><p><p><span style="color: #ff6600;"><span style="color: #000000;">Using examples from producer consumers can be a good understanding of nscondition</span></span></p></p><p><p><span style="color: #008000;">1. The producer wants to obtain the lock, then goes to the production, produces the product to put into the storehouse, if the storehouse is full, then waits, releases the lock, until other thread wakes it to produce, if is not full, then produces the commodity to call signal, may wake up on this condition waits the Thread.</span></p></p><p><p><span style="color: #008000;">2. The consumer wants to obtain the lock, then goes to consume, if does not have the commodity at present, waits, releases the lock, until the thread goes to awaken it to consume, if has the commodity, then will inform the waiting producer to produce the commodity after the Consumption.</span></p></p><p><p><span style="color: #008000;">The key to producers and consumers is: when the warehouse is full, producers wait, no longer continue to produce goods, when the warehouse is empty, consumers wait, no longer continue to consume goods, go to the warehouse has goods, the producers will inform consumption to Consume.</span></p></p><pre class="brush:objc;gutter:true;">-(void) Conditiontest{//create Array Store products = [[nsmutablearray alloc] init]; Condition = [[nscondition alloc] init]; [nsthread detachnewthreadselector: @selector (createproducter) totarget:self withobject:nil]; [nsthread detachnewthreadselector: @selector (createconsumenr) totarget:self withobject:nil];} -(void) createconsumenr{while (1) {//simulate consumer time, make it slower than production [nsthread sleepfortimeinterval:arc4random ()%10 * 0.1 + 1.5]; [condition lock]; While (products.count = = 0) {NSLog (@ "product is 0, waiting for production"); [condition wait]; } [products removelastobject]; NSLog (@ "consumed A commodity, number of items =%ld", products.count); [condition signal]; [condition unlock]; }}-(void) createproducter{while (1) {//analog production product time [nsthread sleepfortimeinterval:arc4random ()%10 * 0. 1 + 0.5]; [condition lock]; While (products.count = = 5) {NSLog (@ "the goods are full, waiting for consumption"); [condition wait]; } [products Addobject:[[nsobject alloc] init]]; NSLog (@ "produced A commodity, the number of goods%ld", products.count); [condition signal]; [condition unlock]; } }</pre><p><p>In addition, send a summary of the picture</p></p><p><p></p></p><p><p>Multi-threaded (iii) Lock in iOS</p></p></span>
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