iOS底层系列之<37>--多线程<七>-锁<3>pthread_mutex_t 基本使用

接着上一篇文章,介绍pthread_mutex_t的用法

#import "pthreadMutexVC.h"
#import <pthread.h>

@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 {
    //    #define PTHREAD_MUTEX_INITIALIZER {_PTHREAD_MUTEX_SIG_init, {0}}
    //    self.mutex = PTHREAD_MUTEX_INITIALIZER;  // 静态初始化方法,所以这里不能用这种方式初始化,用下面👇🏻方法初始化
        // 1.初始化属性
        pthread_mutexattr_t attr;
        pthread_mutexattr_init(&attr);
        /*
         * Mutex type attributes
         */
    //    #define PTHREAD_MUTEX_NORMAL        0
    //    #define PTHREAD_MUTEX_ERRORCHECK    1
    //    #define PTHREAD_MUTEX_RECURSIVE        2
    //    #define PTHREAD_MUTEX_DEFAULT        PTHREAD_MUTEX_NORMAL

//    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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值