多线程自旋锁、互斥锁

2020-10-20  本文已影响0人  Jean_Lina

semaphore:信号量
recursive:递归的
unfair:不公平
mutex:互斥

OSSpinLock:自旋锁,等待锁的线程一直处于忙等状态,一直占有着CPU资源。

os_unfair_lock:替代自旋锁,等待锁的线程处于休眠状态,不占有着CPU资源。

pthread_mutex_t:互斥锁,等待锁的线程处于休眠状态,不占有着CPU资源。

递归锁:允许同一条线程对一把锁进行重复加锁。

semaphore 信号量
信号量的初始值,可以用来控制线程并发访问的最大数量。
信号量的初始值为1,代表同时只允许有一条线程访问资源,保证线程同步。

OSSpinLock:自旋锁

#import <libkern/OSAtomic.h>
@property (nonatomic, assign) OSSpinLock moneyLock;
@property (nonatomic, assign) OSSpinLock ticketLock;
- (instancetype)init
{
    self = [super init];
    if (self) {
        _moneyLock = OS_SPINLOCK_INIT;
        _ticketLock = OS_SPINLOCK_INIT;
    }
    return self;
}
- (void)saveMoney {
    OSSpinLockLock(&_moneyLock);
    [super saveMoney];
    OSSpinLockUnlock(&_moneyLock);
}
- (void)drawMoney {
    OSSpinLockLock(&_moneyLock);
    [super drawMoney];
    OSSpinLockUnlock(&_moneyLock);
}

//- (void)saleTicket {
//    OSSpinLockLock(&_ticketLock);
//    [super saleTicket];
//    OSSpinLockUnlock(&_ticketLock);
//}
- (void)saleTicket {
    //通过静态变量定义锁
    static OSSpinLock ticketLock1 = OS_SPINLOCK_INIT;
    OSSpinLockLock(&ticketLock1);
    [super saleTicket];
    OSSpinLockUnlock(&ticketLock1);
}

os_unfair_lock:

#import <os/lock.h>
//通过属性定义锁
@property (nonatomic, assign) os_unfair_lock moneyLock;
@property (nonatomic, assign) os_unfair_lock ticketLock;
- (instancetype)init
{
    self = [super init];
    if (self) {
        _moneyLock = OS_UNFAIR_LOCK_INIT;
        _ticketLock = OS_UNFAIR_LOCK_INIT;
    }
    return self;
}
- (void)saveMoney {
    os_unfair_lock_lock(&_moneyLock);
    [super saveMoney];
    os_unfair_lock_unlock(&_moneyLock);
}
- (void)drawMoney {
    os_unfair_lock_lock(&_moneyLock);
    [super drawMoney];
    os_unfair_lock_unlock(&_moneyLock);
}
- (void)saleTicket {
    os_unfair_lock_lock(&_ticketLock);
    [super saleTicket];
    os_unfair_lock_unlock(&_ticketLock);
}

pthread_mutex_t:互斥锁

#import <pthread.h>
@property (nonatomic, assign) pthread_mutex_t moneyLock;
@property (nonatomic, assign) pthread_mutex_t ticketlock;
- (instancetype)init
{
    self = [super init];
    if (self) {
        [self initMutex:&_moneyLock];
        [self initMutex:&_ticketlock];
    }
    return self;
}
- (void)initMutex:(pthread_mutex_t *)mutex {
    pthread_mutexattr_t attr;
    pthread_mutexattr_init(&attr);
    //定义锁的类型:递归锁(存在递归调用,定义递归锁),普通锁
    pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
    pthread_mutex_init(mutex, &attr);
    pthread_mutexattr_destroy(&attr);
}
- (void)saveMoney {
    pthread_mutex_lock(&_moneyLock);
    [super saveMoney];
    pthread_mutex_unlock(&_moneyLock);
}
- (void)drawMoney {
    pthread_mutex_lock(&_moneyLock);
    [super drawMoney];
    pthread_mutex_unlock(&_moneyLock);
}
- (void)saleTicket {
    pthread_mutex_lock(&_ticketlock);
    [super saleTicket];
    pthread_mutex_unlock(&_ticketlock);
}
- (void)dealloc
{
    pthread_mutex_destroy(&_moneyLock);
    pthread_mutex_destroy(&_ticketlock);
}
上一篇下一篇

猜你喜欢

热点阅读