首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >无法在ConcurrentLinkedQueue源代码中获取此条件

无法在ConcurrentLinkedQueue源代码中获取此条件
EN

Stack Overflow用户
提问于 2018-01-18 18:28:10
回答 2查看 175关注 0票数 5

在ConcurrentLinkedQueue的源代码中,offer方法中:

代码语言:javascript
复制
public boolean offer(E e) {
checkNotNull(e);
final Node<E> newNode = new Node<E>(e);

for (Node<E> t = tail, p = t;;) {
    Node<E> q = p.next;
    if (q == null) {
        // p is last node
        if (p.casNext(null, newNode)) {
                // Successful CAS is the linearization point
                // for e to become an element of this queue,
                // and for newNode to become "live".
                if (p != t) // hop two nodes at a time
                    casTail(t, newNode);  // Failure is OK.
                    return true;
            }
            // Lost CAS race to another thread; re-read next
        }
        else if (p == q)
            // We have fallen off list.  If tail is unchanged, it
            // will also be off-list, in which case we need to
            // jump to head, from which all live nodes are always
            // reachable.  Else the new tail is a better bet.
            p = (t != (t = tail)) ? t : head;
        else
            // Check for tail updates after two hops.
            p = (p != t && t != (t = tail)) ? t : q;
    }
}

在第352行,有这样的条件:

代码语言:javascript
复制
p = (p != t && t != (t = tail)) ? t : q;

我知道代码是为了把p放在尾部,但为什么要用这么复杂的代码呢?那么(p != t && t != (t = tail))是什么意思呢?t!=(t=tail))t!=t有什么不同?它应该总是假的吗?

有没有什么资料可以清楚地解释ConcurrentLinkedQueue?

EN

回答 2

Stack Overflow用户

发布于 2018-01-18 18:57:37

这是一个有趣的问题,我asked it more broadly there并得到了一些答案。从我能读到的这个话题上看:

t != (t = tail)只是一种奇怪的写法:

代码语言:javascript
复制
if (t != tail)
    t = tail;

简而言之,您正在将t的值与分配给右侧t的值(此处为tail )进行比较。

(所有的荣誉都归功于Eran对这个话题的理解和他的回答)

因此,完整地回答您的问题:

我不知道他们为什么用这么复杂的code.

  • (p != t && t != (t = tail)),意思是if p != t and if t != tail t takes the tail value

  • Difference,,
  • ,It,

  • ,It,

,。

票数 0
EN

Stack Overflow用户

发布于 2018-01-18 18:35:24

因此,我认为另一个线程可能正在操作之间进行更新,

代码语言:javascript
复制
t != (t = tail))

正在检查,并且正在测试。它必须以某种方式依赖于原子才能有用

编辑:

回复Yassine Badache的反对票,这似乎是正确的

代码语言:javascript
复制
t = tail

是一个赋值运算符

此外,

代码语言:javascript
复制
if

语句用于根据条件对代码进行分支,

代码语言:javascript
复制
(x = y)

返回对x的引用,如(通过检查,任何使用过c的人都能清楚地看到)

代码语言:javascript
复制
if ((p = fopen(f)) == NULL)

我认为OP是关于Java(或任何人)的并发功能的内部实现

编辑:

我认为这是Java和/或folly实现中的错误

票数 -2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48319047

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档