0422 thread sync/sync lock to prevent dirty data

Source: Internet
Author: User

If the lock is not synchronized, the code is as follows: #import "ViewController.h"

@interface Viewcontroller ()
{
Nsinteger _money;
}

@end

@implementation Viewcontroller

-(void) Viewdidload {
[Super Viewdidload];

_money = 100;

Nsthread *t1 = [[Nsthread alloc]initwithtarget:self selector: @selector (dothing) Object:nil];
Nsthread *t2 = [[Nsthread alloc]initwithtarget:self selector: @selector (dothing) Object:nil];
Nsthread *t3 = [[Nsthread alloc]initwithtarget:self selector: @selector (dothing) Object:nil];
Nsthread *T4 = [[Nsthread alloc]initwithtarget:self selector: @selector (dothing) Object:nil];
T1.name = @ "I am--t1";
T2.name = @ "I am--t2";
T3.name = @ "I am--t3";
T4.name = @ "I am--t4";

[T1 start];
[T2 start];
[T3 start];
[T4 start];


}

-(void) dothing{

for (int. i=0;i<3;i++) {[Self getmoney:10]; }  }

-(void) Getmoney: (Nsinteger) money{

Check balance

if (_money >= money) {

[Nsthread Sleepfortimeinterval:2];

_money-= money;

NSLog (@ "%@----Balance:%ld", [Nsthread Currentthread],_money); }}//print results, random: obvious dirty data//improvements: Thread Lock: 1. Create a Lock object Nslock, and instantiate _lockcondition = [[Nslock alloc]init];2. Determine if there is a lock, do not enter and lock. if ([_lockcondition Trylock]) {//In the inside do take money operation//withdraw money after the completion of the unlock [_lockcondition unlock];} After the improvement: a total of 12 times, only 4 times the operation was successful. 0422_ Review _ thread synchronization. zip
25.0 KB
Requirements: If you really want to take the money, it should be as follows: //locking, unlock after operation is complete.Visible: After locking, both the operator and the operating thread are orderly ...

0422 thread sync/sync lock to prevent dirty data

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.