-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathrcobjectwfopt.h
80 lines (66 loc) · 1.51 KB
/
rcobjectwfopt.h
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
70
71
72
73
74
75
76
77
78
79
80
/// TODO
#pragma once
#include <atomic>
#include <iostream>
namespace rcwfopt
{
template <typename T>
class RCWaitFreeOpt
{
static constexpr size_t SINGLE_RC = 4;
static constexpr size_t WEAK = 2;
static constexpr size_t CLOSED = 1;
std::atomic<size_t> strong{SINGLE_RC};
std::atomic<size_t> weak{0};
T body;
public:
template <typename... Args>
RCWaitFreeOpt(Args &&...args)
: body(std::forward<Args>(args)...) {}
void release_weak()
{
if ((weak == 1) || (--weak == 0))
free(this);
}
void release_strong() {
auto old = strong.fetch_sub(SINGLE_RC);
if (old > (SINGLE_RC + WEAK))
return;
if ((old & WEAK) == 0) {
body.~T();
free(this);
return;
}
old = WEAK;
if (strong.compare_exchange_strong(old, CLOSED))
body.~T();
release_weak();
}
void acquire_weak() {
size_t old = weak;
if (old == 0) {
if (weak.compare_exchange_strong(old, 2)) {
strong += WEAK;
return;
}
}
weak++;
}
void acquire_strong()
{
strong.fetch_add(SINGLE_RC);
}
bool acquire_strong_from_weak()
{
auto old = strong.fetch_add(SINGLE_RC);
if ((old & CLOSED) != 0)
return false;
if (old < SINGLE_RC)
acquire_weak();
return true;
}
};
template <typename T>
using RCObject = RCWaitFreeOpt<T>;
static inline std::string Flavour = "Wait-free (Opt)";
} // namespace rcwf