xxxxxxxxxx
NSConditionLock *lock = [[NSConditionLock alloc]init];
NSMutableArray *products = [NSMutableArray array];
NSUInteger pdt_cnt_state_0 = 0; // 初始条件
NSUInteger pdt_cnt_state_1 = 1; // 当前有数据量是4
NSUInteger pdt_cnt_state_2 = 2; // 当前有数据是12
NSUInteger pdt_cnt_state_3 = 3; // 当前数据是 18
// 这里主要是为了自增数据
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
while (1) {
[lock lockWhenCondition:pdt_cnt_state_0];
NSLog(@"add product ----- ");
[products addObject:[[NSObject alloc] init]];
[products addObject:[[NSObject alloc] init]];
[products addObject:[[NSObject alloc] init]];
[products addObject:[[NSObject alloc] init]];
NSLog(@"---------- total product,数组总数量 = %zi",products.count);
if (products.count == 4) {
// 达到第一个条件,释放条件信号
[lock unlockWithCondition:pdt_cnt_state_1];
}else if (products.count == 10){
// 达到第二个条件,释放条件信号
[lock unlockWithCondition:pdt_cnt_state_2];
}else if (products.count == 16){
// 达到第三个条件,释放条件信号
[lock unlockWithCondition:pdt_cnt_state_3];
}else{
// 释放条件信息, 即继续addObject
[lock unlockWithCondition:pdt_cnt_state_0];
}
sleep(1);
}
});
// 条件一
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
while (1) {
[lock lockWhenCondition:pdt_cnt_state_1];
NSLog(@"****进入条件一 state_1");
// 删除两条数据
[products removeObjectAtIndex:0];
[products removeObjectAtIndex:0];
NSLog(@"state_1 current = %zi",products.count);
// 返回继续增加数据
[lock unlockWithCondition:pdt_cnt_state_0];
sleep(1);
}
});
// 条件二
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
while (1) {
[lock lockWhenCondition:pdt_cnt_state_2];
NSLog(@"****进入条件二 state_2");
// 删除两条数据
[products removeObjectAtIndex:0];
[products removeObjectAtIndex:0];
NSLog(@"state_2 current = %zi",products.count);
// 返回继续增加数据
[lock unlockWithCondition:pdt_cnt_state_0];
sleep(1);
}
});
// 条件三
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
while (1) {
[lock lockWhenCondition:pdt_cnt_state_3];
NSLog(@"****into state_3");
// 删除两条数据
[products removeObjectAtIndex:0];
[products removeObjectAtIndex:0];
NSLog(@"state_3 current = %zi",products.count);
// 返回继续增加数据
[lock unlockWithCondition:pdt_cnt_state_0];
sleep(1);
}
});