-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhazptr_domain.cpp
69 lines (62 loc) · 2.15 KB
/
hazptr_domain.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#include "hazptr_domain.hpp"
namespace HazardPointer
{
template <class T, class D>
HazPtr<T>* HazPtrDomain<T, D>::acquire() const
{
// Walk the list of hazard pointers and
auto& head_ptr = hazptrs.head;
auto node = head_ptr.load(std::memory_order_seq_cst);
while (true)
{
// If the active flag is set, we cannot use that node
while (node && node.active.load(std::memory_order_seq_cst))
{
node = node.next.load(std::memory_order_seq_cst);
}
// If we get a nullptr, we don't have any hazard pointers to reuse
// and we need to allocate.
if (!node)
{
// No free HazPtrs -- need to allocate a new one
// HazPtr(ptr, next, active)
HazPtr hazptr(nullptr, nullptr, true);
auto head = head_ptr.load(std::memory_order_seq_cst);
// And stick it at the head of the linked list
while (true)
{
hazptr.next = head;
// Compare and swap the head ptr
if (std::atomic_compare_exchange_weak(head_ptr, head, hazptr))
{
// Safety: will never be de-allocated
// Return the mem address of the new hazptr
return &hazptr;
} else {
// Head has changed, try again with that as our
// next ptr.
continue;
}
}
}
else
{
if (std::atomic_compare_exchange_weak(&node.active, false, true))
{
// It's ours
return &node;
}
else
{
// Someone else grabbed this node right before us
// Keep walking
}
}
}
}
template <class T, class D>
void HazPtrDomain<T, D>::retire(D d, T* ptr) const
{
// TODO
}
}