下面是使用compareAndSet来自无锁队列一些代码(在Java中):这些行是否在无锁队列中不是必需的?
public void enq(T value) {
Node newNode = new Node(value);
while(true) {
Node last = tail.get();
Node next = last.next.get();
if(last != tail.get())
continue; //???
if (next != null) { //improve tail
tail.compareAndSet(last, next);
continue;
}
if (last.next.compareAndSet(null, newNode)) { //update last node
tail.compareAndSet(last, newNode); //update tail
return;
}
}
}
public T deq() throws EmptyException {
while(true) {
Node first = head.get();
Node last = tail.get();
Node next = first.next.get();
if(first != head.get())
continue; //???
if(first == last) {
if (next == null)
throw new EmptyException();
tail.compareAndSet(last, next);
continue;
}
T value = next.value;
if (head.compareAnsdSet(first, next)) {
return value;
}
}
}
(头部和尾部是队列的成员)
在这两个DEQ和ENQ功能,第一次检查似乎对我没有必要。 (那些评论“???”) 我怀疑它只是为了某种优化。
我在这里错过了什么吗?这些检查会影响代码的正确性吗?
(代码是从“的多处理器编程艺术”拍摄,虽然我没有重构代码风格有较少的嵌套如果和别人的,同时保持代码的等价物)
他们似乎在检查局部变量是否已经被一致地设置,但是我会把它留给其他人来回答它们是否会影响代码的正确性。 – 2011-03-23 13:24:44