0422 线程同步/同步锁防止脏数据

如果不加同步锁,代码如下:
#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 = @"我是--t1";
    t2.name = @"我是--t2";
    t3.name = @"我是--t3";
    t4.name = @"我是--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{
   
    // 查余额
   
    if(_money >= money){
       
        [NSThread sleepForTimeInterval:2];
       
        _money -= money;
       
        NSLog(@"%@----余额 : %ld",[NSThread currentThread],_money);
    }
}
// 打印结果,有随机性: 明显脏数据
 
// 改进:
线程锁:
1. 创建锁对象NSLock,并实例化
_lockCondition = [[NSLock alloc]init];
2. 判断是否有锁,没有就进入并锁住.
if ([_lockCondition tryLock]) {
// 在里面做取钱操作
// 取钱完成后解锁
    [_lockCondition unlock];
}
改进后:总共12次,只有4次取钱操作成功了.
 

 
// 需求: 如果确实要取完钱为止
应该按如下方式:
//加锁,操作完成后解锁.
// 可见: 加锁后, 操作者和操作线程都是有序的...
posted @ 2015-04-23 00:49  toxicanty  阅读(210)  评论(0编辑  收藏  举报