在ConcurrentLinkedQueue的源代码中,offer方法中:
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行,有这样的条件:
p = (p != t && t != (t = tail)) ? t : q;我知道代码是为了把p放在尾部,但为什么要用这么复杂的代码呢?那么(p != t && t != (t = tail))是什么意思呢?t!=(t=tail))和t!=t有什么不同?它应该总是假的吗?
有没有什么资料可以清楚地解释ConcurrentLinkedQueue?
发布于 2018-01-18 18:57:37
这是一个有趣的问题,我asked it more broadly there并得到了一些答案。从我能读到的这个话题上看:
t != (t = tail)只是一种奇怪的写法:
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
,
,
,。
发布于 2018-01-18 18:35:24
因此,我认为另一个线程可能正在操作之间进行更新,
t != (t = tail))正在检查,并且正在测试。它必须以某种方式依赖于原子才能有用
编辑:
回复Yassine Badache的反对票,这似乎是正确的
t = tail是一个赋值运算符
此外,
if语句用于根据条件对代码进行分支,
(x = y)返回对x的引用,如(通过检查,任何使用过c的人都能清楚地看到)
if ((p = fopen(f)) == NULL)我认为OP是关于Java(或任何人)的并发功能的内部实现
编辑:
我认为这是Java和/或folly实现中的错误
https://stackoverflow.com/questions/48319047
复制相似问题