次に、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;
}
}
}
(head と tail はキューのメンバーです)
deq 関数と enq 関数の両方で、最初のチェックは不要に思えます。("???" でコメントしたもの) ある種の最適化のためだけにあるのではないかと思います。
ここで何か不足していますか?これらのチェックはコードの正確さに影響しますか?
(コードは「Art of Multi-processor Programming」から取られていますが、コード スタイルをリファクタリングして、ネストされた if と else を減らし、コードを同等に保ちます)