接着上一篇文章,介绍pthread_mutex_t的用法
@interface pthreadMutexVC ()
@property (assign, nonatomic) pthread_mutex_t lock1;
@property (assign, nonatomic) pthread_mutex_t lock2;
@end
@implementation pthreadMutexVC
- (void)viewDidLoad {
[super viewDidLoad];
[self __initMutex:&_lock1];
[self __initMutex:&_lock2];
[self concurrentMoney];
[self concurrentSaleTicket];
}
- (void)__initMutex:(pthread_mutex_t *)mutex {
//
// self.mutex = PTHREAD_MUTEX_INITIALIZER; // 静态初始化方法,所以这里不能用这种方式初始化,用下面👇🏻方法初始化
// 1.初始化属性
pthread_mutexattr_t attr;
pthread_mutexattr_init(&attr);
/*
* Mutex type attributes
*/
//
//
//
//
// pthread_mutexattr_settype(&attr, NULL); 传空,默认 PTHREAD_MUTEX_DEFAULT
pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_DEFAULT);
// 2.初始化锁
pthread_mutex_init(mutex, &attr);
// 3.销毁属性
pthread_mutexattr_destroy(&attr);
}
- (void)__saveMoney {
pthread_mutex_lock(&_lock1);
[super saveMoney];
pthread_mutex_unlock(&_lock1);
}
- (void)__drawMoney {
pthread_mutex_lock(&_lock1);
[super drawMoney];
pthread_mutex_unlock(&_lock1);
}
- (void)__saleTicket {
pthread_mutex_lock(&_lock2);
[super saleTicket];
pthread_mutex_unlock(&_lock2);
}
- (void)concurrentMoney {
dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
dispatch_async(queue, ^{
for (int i = 0; i < 10; i++) {
[self __saveMoney];
}
});
dispatch_async(queue, ^{
for (int i = 0; i < 10; i++) {
[self __drawMoney];
}
});
}
- (void)concurrentSaleTicket {
dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
dispatch_async(queue, ^{
for (int i = 0; i < 5; i++) {
[self __saleTicket];
}
});
dispatch_async(queue, ^{
for (int i = 0; i < 5; i++) {
[self __saleTicket];
}
});
}
- (void)dealloc {
// 不用需要销毁
pthread_mutex_destroy(&_lock1);
pthread_mutex_destroy(&_lock2);
}
@end