关于CAS在aqs中的应用

来源:7-1 什么是CAS

Screenly

2021-05-14

关于CAS在aqs中的应用

在使用ReentrantLock时,多个线程抢占资源,未能cas成功的线程会进入asq的等待队列,代码如下

private Node enq(final Node node) {
        for (;;) {
            Node t = tail;
            if (t == null) { // Must initialize
                if (compareAndSetHead(new Node()))
                    tail = head;
            } else {
                node.prev = t;
                if (compareAndSetTail(t, node)) {
                    t.next = node;
                    return t;
                }
            }
        }
    }

// CAS操作
  /**
   * CAS tail field. Used only by enq.
   */
  private final boolean compareAndSetTail(Node expect, Node update) {
      return unsafe.compareAndSwapObject(this, tailOffset, expect, update);
  }    

我的问题是: 在理解cas的时候, 比如:compareAndSetTail(t, node), 这段代码的还以就是,如果 t 与 tailOffset 的偏移量相等, 那么就将 t 真正改为 node, 这样理解正确吗?

写回答

1回答

悟空

2021-05-15

你理解的是对的,其实就和一般的CAS的含义是一样的。

0
0

深度解密Java并发工具,精通JUC,成为并发多面手

JUC全方位讲解,构建并发工具类知识体系

1599 学习 · 573 问题

查看课程