編集:気づいたように、私はまったく反対のセマンティクスで関数を書きました-空のキューにのみエンキューします。それを反映するために名前を修正し、誰かが興味を持った場合に備えてそのままにしておくことにしました. したがって、これは質問に対する正しい答えではありませんが、別の理由が見つからない限り、反対票を投じないでください:)
EnqueueIfEmpty()
以下は、参照された論文のキュー実装に追加する試みです。動作するか、コンパイルできるかは確認していません。基本的な考え方は、head の next が現在 null である場合 (空のキューに必要な条件)、headの直後に (tail ではなく) 新しいノードを挿入することです。頭が尾と等しいことを確認する追加のチェックを残しましたが、これは削除できる可能性があります。
public bool EnqueueIfEmpty(T item) {
// Return immediately if the queue is not empty.
// Possibly the first condition is redundant.
if (head!=tail || head.Next!=null)
return false;
SingleLinkNode<T> oldHead = null;
// create and initialize the new node
SingleLinkNode<T> node = new SingleLinkNode<T>();
node.Item = item;
// loop until we have managed to update the tail's Next link
// to point to our new node
bool Succeeded = false;
while (head==tail && !Succeeded) {
// save the current value of the head
oldHead = head;
// providing that the tail still equals to head...
if (tail == oldHead) {
// ...and its Next field is null...
if (oldhead.Next == null) {
// ...try inserting new node right after the head.
// Do not insert at the tail, because that might succeed
// with a non-empty queue as well.
Succeeded = SyncMethods.CAS<SingleLinkNode<T>>(ref head.Next, null, node);
}
// if the head's Next field was non-null, another thread is
// in the middle of enqueuing a new node, so the queue becomes non-empty
else {
return false;
}
}
}
if (Succeeded) {
// try and update the tail field to point to our node; don't
// worry if we can't, another thread will update it for us on
// the next call to Enqueue()
SyncMethods.CAS<SingleLinkNode<T>>(ref tail, oldHead, node);
}
return Succeeded;
}