lock底层源码

8 篇文章 0 订阅
3 篇文章 0 订阅

ReetrantLock分为公平锁和非公平锁

public static void main(String[] args) {
    Lock lock = new ReentrantLock();
    lock.lock();
    lock.unlock();
}

非公平枪锁机制

public ReentrantLock() {    // ReentrantLock默认是创建非公平锁
    sync = new NonfairSync();
}

// lock.lock();
public void lock() {
    sync.lock();
}
final void lock() {
    if (compareAndSetState(0, 1))    // 非公平锁上来就强行获取锁一次 
        setExclusiveOwnerThread(Thread.currentThread());    // 抢锁成功着修改lock锁占用的线程
    else
        acquire(1);    
}

protected final void setExclusiveOwnerThread(Thread thread) {
    exclusiveOwnerThread = thread;
}

// 加入队列并进行自旋等待
public final void acquire(int arg) {
    if (!tryAcquire(arg) &&    // 再次抢锁,并且判断占用锁资源的线程是否是当前线程
        acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
        selfInterrupt();
}

protected final boolean tryAcquire(int acquires) {// 再次抢锁
    return nonfairTryAcquire(acquires);
}

final boolean nonfairTryAcquire(int acquires) {
    final Thread current = Thread.currentThread();
    int c = getState();    // 获取lock状态
    if (c == 0) {    // 如果等于0表示无锁状态
        if (compareAndSetState(0, acquires)) {    // 再次枪锁
            setExclusiveOwnerThread(current);
            return true;
        }
    }
    else if (current == getExclusiveOwnerThread()) {    // 判断当前占用锁线程是否是当前线程,如果是就重入锁
        int nextc = c + acquires;
        if (nextc < 0) // overflow
            throw new Error("Maximum lock count exceeded");
        setState(nextc);
        return true;
    }
    return false;
}

// 加入队列并进行自旋等待
// acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
// 添加一个互斥锁的节点
private Node addWaiter(Node mode) {
    Node node = new Node(Thread.currentThread(), mode);    // 当前线程创建node
    // Try the fast path of enq; backup to full enq on failure
    Node pred = tail;    //尾节点
    if (pred != null) {       // 尾节点不为空并且假设不存在竞争的情况修改
        node.prev = pred;    // 当前node节点prev指向上一个节点
        if (compareAndSetTail(pred, node)) {    //cas 比较修改尾节点指向当前节点
            pred.next = node;    //上一个节点的next下个节点指向当前node节点
            return node;
        }
    }
    enq(node);    // 竞争后和尾节点为空的情况下进去
    return node;
}

private Node enq(final Node node) {    // 查看图一添加队列状态
    for (;;) {// 自旋
        Node t = tail;
        if (t == null) { // 尾为空,初始化
            if (compareAndSetHead(new Node()))
                tail = head;
        } else {
            node.prev = t;    // 当前node节点prev指向上一个节点
            if (compareAndSetTail(t, node)) {    //比较修改尾节点指向当前节点
                t.next = node;    // 上一个节点的next下个节点指向当前node节点
                return t;
            }
        }
    }
}

图1
在这里插入图片描述

公平锁枪锁机制

public ReentrantLock(boolean fair) {    // Lock lock = new ReentrantLock(true); 创建对象传true
    sync = fair ? new FairSync() : new NonfairSync();
}
final void lock() {
    acquire(1);
}
public final void acquire(int arg) {
    if (!tryAcquire(arg) &&    // 抢锁
        acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
        selfInterrupt();
}
protected final boolean tryAcquire(int acquires) {
        final Thread current = Thread.currentThread();
        int c = getState();
        if (c == 0) {    // 无锁状态
            if (!hasQueuedPredecessors() && // 校验队列当中是否有其他线程等待
                compareAndSetState(0, acquires)) {    // CAS(#Lock) -> 原子操作| 实现互斥的判断
                setExclusiveOwnerThread(current);    // 修改lock为当前线程
                return true;
            }
        }
        else if (current == getExclusiveOwnerThread()) {     // 判断当前占用锁资源线程和当前抢锁线程是同一个,如果是就重入锁
            int nextc = c + acquires;
            if (nextc < 0)
                throw new Error("Maximum lock count exceeded");
            setState(nextc);// 重入次数添加
            return true;
        }
        return false;    // false表示抢锁失败
    }
}

// 加入队列并进行自旋等待
//    acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
// 添加一个互斥锁的节点
private Node addWaiter(Node mode) {    //非公平锁和公平锁添加队列都是同一个
    Node node = new Node(Thread.currentThread(), mode);    // 当前线程创建node
    // Try the fast path of enq; backup to full enq on failure
    Node pred = tail;    //尾节点
    if (pred != null) {       // 尾节点不为空并且假设不存在竞争的情况修改
        node.prev = pred;    // 当前线程node的上一个指向tail尾节点
        if (compareAndSetTail(pred, node)) {    //cas 比较两个节点指向修改成功
            pred.next = node;    //尾节点
            return node;
        }
    }
    enq(node);    // 竞争后和尾节点为空的情况下进去
    return node;
}

private Node enq(final Node node) {    // 查看图一添加队列状态
    for (;;) {// 自旋
        Node t = tail;
        if (t == null) { // 尾为空,初始化
            if (compareAndSetHead(new Node()))
                tail = head;
        } else {
            node.prev = t;
            if (compareAndSetTail(t, node)) {    //比较修改头节点
                t.next = node;
                return t;
            }
        }
    }
}

公平锁和非公平锁排队阻塞

final boolean acquireQueued(final Node node, int arg) {    // 获取排队
    boolean failed = true;
    try {
        boolean interrupted = false;
        for (;;) {    // 自选抢锁
            final Node p = node.predecessor(); 
            if (p == head && tryAcquire(arg)) {// 判断当前是否是第一个线程在队列当中,如果是着尝试去获得锁
                setHead(node);    // 抢锁成功抛弃空node节点,从新指向,
                p.next = null; // help GC
                failed = false;
                return interrupted;
            }
            // 否则,让线程去阻塞(park)
            if (shouldParkAfterFailedAcquire(p, node) &&    
                parkAndCheckInterrupt()) // 在循环第二次shouldParkAfterFailedAcquire(p, node)方法后会返回true执行这段代码,阻塞
                interrupted = true;
        }
    } finally {
        if (failed)
            cancelAcquire(node);
    }
}

// 修改当前node的waitStatus状态
private static boolean shouldParkAfterFailedAcquire(Node pred, Node node) {
    int ws = pred.waitStatus;    // The field is initialized to 0 for normal sync nodes常的同步节点,该字段被初始化为0
    if (ws == Node.SIGNAL)// waitStatus value to indicate successor's thread needs unparking 当前状态如果为-1 值表示后继线程需要唤醒
        return true;
    if (ws > 0) {// waitStatus value to indicate thread has cancelled 大于0  值表示线程已经取消
        do {
            node.prev = pred = pred.prev; // 表示当前node节点前后指向改变
        } while (pred.waitStatus > 0); // 查看图2
        pred.next = node;
    } else {
        compareAndSetWaitStatus(pred, ws, Node.SIGNAL); // 修改当前node状态为Node.SIGNAL -1
    }
    return false;
}

private final boolean parkAndCheckInterrupt() {
    LockSupport.park(this);    // 被中断唤醒
    return Thread.interrupted();    // 表示中断状态(是否是中断唤醒的)
}
// 抢锁成功后的节点指向
private void setHead(Node node) {
    head = node;
    node.thread = null;
    node.prev = null;
}

图2
在这里插入图片描述
图3
在这里插入图片描述

公平锁和非公平锁释放锁资源

// lock.unlock();

public void unlock() {
    sync.release(1);
}
public final boolean release(int arg) {
    if (tryRelease(arg)) {
        Node h = head;
        if (h != null && h.waitStatus != 0)    // 如果队列中头节点不为空,并且当前node节点waitStatus状态不为默认值0
            unparkSuccessor(h);
        return true;
    }
    return false;
}

protected final boolean tryRelease(int releases) {    //释放锁只有一个线程释放
    int c = getState() - releases;    // 扣减重入次数
    if (Thread.currentThread() != getExclusiveOwnerThread())
        throw new IllegalMonitorStateException();
    boolean free = false;
    if (c == 0) {    // 如果为0着清除 Thread当前状态为null
        free = true;
        setExclusiveOwnerThread(null);
    }
    setState(c);    // 修改锁为占用
    return free;
}

private void unparkSuccessor(Node node) {
    int ws = node.waitStatus;
    if (ws < 0) //当前node的waitStatus如果为-1表示需要修改为0
        compareAndSetWaitStatus(node, ws, 0);
    Node s = node.next;
    if (s == null || s.waitStatus > 0) {   // 如果当前node的下一个节点为空或者是需要抛弃的节点着进入其中修改
        s = null;
        for (Node t = tail; t != null && t != node; t = t.prev)
            if (t.waitStatus <= 0)    // 查询到小于等于0的那个节点,就是队列当中第一个线程A
                s = t;
    }
    if (s != null)    
        LockSupport.unpark(s.thread);// 当前node节点唤醒
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
unique_lock 是 C++11 中新增的一种互斥量封装类,用于更方便地管理互斥量的加锁和解锁。它的源码实现在 <mutex> 头文件中。 unique_lock 是一个模板类,定义如下: ```c++ template<class Mutex> class unique_lock { public: // 构造函数 explicit unique_lock(Mutex& m); unique_lock(Mutex& m, defer_lock_t); unique_lock(Mutex& m, try_to_lock_t); unique_lock(Mutex& m, adopt_lock_t); template<class Clock, class Duration> unique_lock(Mutex& m, const chrono::time_point<Clock, Duration>& abs_time); template<class Rep, class Period> unique_lock(Mutex& m, const chrono::duration<Rep, Period>& rel_time); // 析构函数 ~unique_lock(); // 成员函数 void lock(); bool try_lock(); void unlock(); void swap(unique_lock& other) noexcept; bool owns_lock() const noexcept; explicit operator bool() const noexcept; // 禁止拷贝和赋值 unique_lock(const unique_lock&) = delete; unique_lock& operator=(const unique_lock&) = delete; // 友元函数 template<class Mutex2> friend class unique_lock; }; ``` unique_lock 有多个构造函数,用于不同的场景:默认构造函数会创建一个未关联互斥量的 unique_lock 对象;explicit unique_lock(Mutex& m) 构造函数会创建一个关联了互斥量 m 的 unique_lock 对象,并立即对互斥量进行加锁;unique_lock(Mutex& m, try_to_lock_t) 构造函数会尝试对互斥量 m 进行加锁,如果加锁失败则不会阻塞线程,而是立即返回 false;unique_lock(Mutex& m, adopt_lock_t) 构造函数会创建一个 unique_lock 对象,但是假设调用者已经对互斥量 m 进行加锁,因此 unique_lock 对象不会再对互斥量进行加锁,而是认为互斥量已经被加锁了;unique_lock(Mutex& m, const chrono::time_point<Clock, Duration>& abs_time) 和 unique_lock(Mutex& m, const chrono::duration<Rep, Period>& rel_time) 构造函数会尝试在指定的时间内对互斥量进行加锁。 unique_lock 的成员函数包括: - lock():对关联的互斥量进行加锁。 - try_lock():尝试对关联的互斥量进行加锁,如果加锁成功则返回 true,否则返回 false。 - unlock():对关联的互斥量进行解锁。 - swap(unique_lock& other):交换两个 unique_lock 对象的状态。 - owns_lock():返回当前 unique_lock 对象是否拥有互斥量的所有权。 - operator bool():返回当前 unique_lock 对象是否拥有互斥量的所有权。 此外,unique_lock 还有一个特殊的成员函数,用于将 unique_lock 对象转换为 lock_guard 对象: ```c++ template<class Mutex> std::lock_guard<Mutex> unique_lock<Mutex>::release() noexcept; ``` 该函数会将当前 unique_lock 对象所拥有的互斥量的所有权转移到一个新的 lock_guard 对象中,并将当前 unique_lock 对象重置为未关联任何互斥量的状态。 unique_lock 的实现方式与 lock_guard 类似,都是通过 RAII 技术来实现对互斥量的加锁和解锁。不同的是,unique_lock 提供了更加灵活的构造函数和成员函数,可以在更多的场景下使用。此外,unique_lock 还支持线程间传递所有权,这是 lock_guard 所不具备的功能。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值