使用NSCondition对象来控制进程的同步,通过NSCondition对象的操作实现进程间的通信。NSCondition也实现了NSLocking协议,因此也可以调用lock、 unlock来实现线程的同步。NSCondition类提供以下3个方法:
wait——该方法让线程一直等待;signal——唤醒在此NSCondition对象上等待的单个线程;broadcast——唤醒在此NSCondition对象上等待的所有线程
以银行存取款为例:设置一个BOOL类型的flag来标识庄户中是否已有存款。NO表示没有存款,存款线程可以向下执行,当存款者把钱存入账户后,设置flag为YES,并调用sinal或broadcast方法唤醒其他线程;当存款者线程进入线程体后,若flag=YES,调用wait方法让改线程等待。当flag为YES时,表明账户中已有存款,取钱线程可以向下执行,当取出钱后,将flag设置为NO,并调用signal或broadcast方法唤醒其他线程;当取钱者进入线程后,如果标识为NO,就调用wait方法进行等待。
只有当取钱线程结束后,存款线程才可以存款;同样只有存款线程存款后取钱线程才可以取钱。
定义一个Acount类,里面定义draw和deposit方法,分别实现存取款操作;
#import "Acount.h"
@implementation Acount
NSCondition *cond;
bool flag;
-(id)initWithAccount:(NSString *)acount balanca:(double)balance
{
if(self = [super init])
{
cond = [[NSCondition alloc] init];
_acount = acount;
_balance = balance;
}
return self;
}
-(void)draw:(CGFloat)drawAmount
{
[cond lock];//add lock
if(!flag)
[cond wait];
else{
NSLog(@"%@ 取了%f", [NSThread currentThread].name, drawAmount);
_balance -= drawAmount;
NSLog(@"账户余额为%f", self.balance);
flag =NO;
[cond broadcast];//wake up other threads
}
[cond unlock];
}
-(void)deposit:(CGFloat) depositAmount
{
[cond lock];
if(flag)
[cond wait];
else
{
NSLog(@"%@ 存了 %f", [NSThread currentThread].name, depositAmount);
_balance += depositAmount;
NSLog(@"账户余额为%f", _balance);
flag = YES;
[cond broadcast];//wake up other threads
}
[cond unlock];//open lock
}
@end
在ViewController.h中,生成一个上类的对象,在button的响应方法里面分别创建取钱线程、存款线程,分别调用Acount的存款方法,Acount的取款方法。
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
FKAcount *acount;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
acount = [[FKAcount alloc] initWithAccount:@"小明" balanca:0.0];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)drawDeposit:(id)sender {
NSThread *thread1 = [[NSThread alloc] initWithTarget:self selector:@selector(draw:) object:[NSNumber numberWithFloat:800.0]];
NSThread *thread2 = [[NSThread alloc] initWithTarget:self selector:@selector(draw:) object:[NSNumber numberWithFloat:800.0]];
NSThread *thread3 = [[NSThread alloc] initWithTarget:self selector:@selector(deposit:) object:[NSNumber numberWithFloat:800.0]];
[thread1 start];
[thread2 start];
[thread3 start];
}
-(void)draw:(NSNumber*) drawAmount
{
[NSThread currentThread].name = @"取";
for(int i=0 ;i < 50; i++)
[acount draw:drawAmount.doubleValue];
}
-(void)deposit:(NSNumber *) depositAmount
{
[NSThread currentThread].name = @"存";
for(int i=0; i < 50; i++)
[acount deposit:depositAmount.doubleValue];
}
@end
程序最后被阻塞无法继续向下执行,因为创建2个取款线程共100次取款操作,而1个存钱线程50次操作,程序最后被阻塞。