上一篇介绍了pthread_mutex_t的递归锁,这里将介绍pthread_mutex_t的条件锁的使用
#import "pthreadMutexCondVC.h"
#import <pthread.h>
@interface pthreadMutexCondVC ()
@property (assign, nonatomic) pthread_mutex_t lock;
@property (assign, nonatomic) pthread_cond_t cond;
@property (strong, nonatomic) NSMutableArray *array;
@end
@implementation pthreadMutexCondVC
- (void)viewDidLoad {
[super viewDidLoad];
NSLog(@"pthreadMutexCondVC");
[self __initMutex:&_lock];
pthread_cond_init(&_cond,NULL); // 初始化条件
self.array = [NSMutableArray array];
[self test];
}
- (void)__initMutex:(pthread_mutex_t *)mutex {
pthread_mutexattr_t attr;
pthread_mutexattr_init(&attr);
pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_DEFAULT);
pthread_mutex_init(mutex, &attr);
pthread_mutexattr_destroy(&attr);
}
- (void)test {
[[[NSThread alloc] initWithTarget:self selector:@selector(removeObj) object:nil] start];
sleep(1);
[[[NSThread alloc] initWithTarget:self selector:@selector(addObj) object:nil] start];
}
- (void)removeObj {
NSLog(@"step1---");
pthread_mutex_lock(&_lock);
NSLog(@"step2---");
if (self.array.count == 0) {
NSLog(@"step3---");
pthread_cond_wait(&_cond, &_lock); // 等待条件,再放开这把锁
}
NSLog(@"step9---");
// 开始删除元素
[self.array removeLastObject];
NSLog(@"step10--%@",self.array);
pthread_mutex_unlock(&_lock);
NSLog(@"step11---");
}
- (void)addObj {
NSLog(@"step4---");
pthread_mutex_lock(&_lock);
NSLog(@"step5---");
[self.array addObject:@"a"];
[self.array addObject:@"b"];
NSLog(@"step6--%@",self.array);
sleep(3);
pthread_cond_signal_thread_np(&_cond, &_lock);
NSLog(@"step7---");
pthread_mutex_unlock(&_lock);
NSLog(@"step8---");
}
- (void)dealloc {
// 需要及时销毁
pthread_mutex_destroy(&_lock);
pthread_cond_destroy(&_cond);
}
@end
打印结果及顺序:
2022-01-27 17:28:50.669915+0800 gcd[94125:1245319] pthreadMutexCondVC
2022-01-27 17:28:50.670174+0800 gcd[94125:1245599] step1—
2022-01-27 17:28:50.670513+0800 gcd[94125:1245599] step2—
2022-01-27 17:28:50.670731+0800 gcd[94125:1245599] step3—
2022-01-27 17:28:51.670330+0800 gcd[94125:1245606] step4—
2022-01-27 17:28:51.670463+0800 gcd[94125:1245606] step5—
2022-01-27 17:28:51.670616+0800 gcd[94125:1245606] step6–(
a,
b
)
2022-01-27 17:28:54.671656+0800 gcd[94125:1245606] step7—
2022-01-27 17:28:54.671813+0800 gcd[94125:1245606] step8—
2022-01-27 17:28:54.671842+0800 gcd[94125:1245599] step9—
2022-01-27 17:28:54.671983+0800 gcd[94125:1245599] step10–(
a
)
2022-01-27 17:28:54.672084+0800 gcd[94125:1245599] step11—