EDIT : 눈치 챘을 때, 필자는 꽤 반대되는 의미론을 지닌 함수를 썼다. 즉 빈 큐에 큐잉 만했다. 나는 그것을 반영하기 위해 이름을 고치고 누군가가 관심을 가지기 때문에 그대로두기로 결정했다. 그래서,이 질문에 대한 정답이 아니라 다른 이유 : 아래
참조 된 논문에서 큐 구현에
EnqueueIfEmpty()
을 추가하는 시도를 발견하지 않는 한, 제발 downvote하지 않습니다. 나는 그것이 작동하는지 또는 심지어 컴파일 하는지를 검증하지 않았다. 기본 아이디어는
머리 바로 뒤에 새 노드를 삽입하고 머리글의 다음 문자가 null 인 경우 (빈 큐의 필수 조건 인 경우) 꼬리가 아닌 새 노드를 삽입하는 것입니다. 나는 꼬리와 동등한 머리에 대한 추가 검사를 남겼는데, 아마도 제거 될 수 있습니다.
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;
}
이 코드에는 미묘한 결함이 있습니다. 문서 상태 (http://www.boyet.com/articles/ABAProblem.html)에서 가비지 수집 때문에 C#에서 작동합니다. C에서 ** 작동하지 않을 것입니다 ** –
대기열에있는 노드에서 ABA 문제를 해결 한 참조 계산 시스템을 사용하고 있습니다. 노드가 조기에 해제되지 않는다는 것을 보장합니다. – luke
대기열 요소를 free()로 허용하는 ref 수 기반 솔루션을 발견하지 못했습니다. 내가 freelist에 요소의 반환을 허용 ref를 기반으로 솔루션을 상상할 수 있지만, 그게 전부 야. 참조 카운트 기반의 안전한 메모리 교정 알고리즘을 설계했다고 말하고 있습니까? –