Michael의 공부하고 있습니다. & Scott의 lock-free 큐 알고리즘을 C++로 구현하려고했습니다.설명 Michael & Scott lock-free 큐 alorigthm
하지만 코드에 경주가 있었고 알고리즘에 경쟁이있을 수 있다고 생각합니다. Simple, Fast, and Practical Non-Blocking and Blocking Concurrent Queue Algorithms 을 원래 큐에서 의사 코드는 다음과 같습니다 :
내가 여기 글을 읽어 내보기에
dequeue(Q: pointer to queue_t, pvalue: pointer to data type): boolean
D1: loop // Keep trying until Dequeue is done
D2: head = Q->Head // Read Head
D3: tail = Q->Tail // Read Tail
D4: next = head.ptr->next // Read Head.ptr->next
D5: if head == Q->Head // Are head, tail, and next consistent?
D6: if head.ptr == tail.ptr // Is queue empty or Tail falling behind?
D7: if next.ptr == NULL // Is queue empty?
D8: return FALSE // Queue is empty, couldn't dequeue
D9: endif
// Tail is falling behind. Try to advance it
D10: CAS(&Q->Tail, tail, <next.ptr, tail.count+1>)
D11: else // No need to deal with Tail
// Read value before CAS
// Otherwise, another dequeue might free the next node
D12: *pvalue = next.ptr->value
// Try to swing Head to the next node
D13: if CAS(&Q->Head, head, <next.ptr, head.count+1>)
D14: break // Dequeue is done. Exit loop
D15: endif
D16: endif
D17: endif
D18: endloop
D19: free(head.ptr) // It is safe now to free the old node
D20: return TRUE // Queue was not empty, dequeue succeeded
, 경주는 다음과 같이이다 :
- 스레드 1은 전진 D3으로 이동 한 다음 중지합니다.
- 스레드 2 스레드로 2 다행히 D20에있는 모든 방법을 고급 1.
- 스레드 같은 머리를 읽고, D3에 진출 D19에서 그것을하려고,
- 스레드 1이 계속되고 고급 D4에 head.ptr을 해제
head.ptr->next
을 읽으십시오. 그러나head.ptr
이 이미 스레드 1에 의해 해제되었으므로 충돌이 발생합니다.
그리고 내 C++ 코드는 정말 항상 누군가가 내 실수를 지적하고 약간의 설명을 적어주세요 수 스레드 1
위해 D4에 충돌?