-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.h
69 lines (60 loc) · 1.62 KB
/
utils.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
#ifndef UTILS_H
#define UTILS_H
#include <atomic>
#include <cassert>
//#define TRACE
#ifdef TRACE
#include <iostream>
#endif
template<typename T>
class SharedRW final
{
std::atomic<T*> ptr;
std::atomic_flag slaveWrite;
public:
explicit SharedRW(const T& t)
: ptr(new T(t)), slaveWrite(ATOMIC_FLAG_INIT)
{
assert(std::atomic_is_lock_free(&ptr));
}
~SharedRW() {
T*p = std::atomic_exchange(&ptr, static_cast<T*>(nullptr));
if (p) delete p;
}
T get_slave() {
#ifdef TRACE
std::cerr << __PRETTY_FUNCTION__ << " " << this << std::endl;
#endif
slaveWrite.test_and_set();
T* placeholder = nullptr;
T* p = std::atomic_exchange(&ptr, placeholder);
assert(p);
T r = *p;
bool succ = std::atomic_compare_exchange_strong(&ptr,&placeholder,p);
if (!succ) delete p;
return r;
}
bool set_slave(const T& val) {
#ifdef TRACE
std::cerr << __PRETTY_FUNCTION__ << " " << this << std::endl;
#endif
T* oldPtr = ptr.load();
bool flag = slaveWrite.test_and_set();
if (!flag) return false;
T* newPtr = new T(val);
bool succ = std::atomic_compare_exchange_strong(&ptr,&oldPtr,newPtr);
if (!succ) delete newPtr;
else if (oldPtr) delete oldPtr;
return succ;
}
void set_master(const T& val) {
#ifdef TRACE
std::cerr << __PRETTY_FUNCTION__ << " " << this << std::endl;
#endif
slaveWrite.clear();
T* newPtr = new T(val);
T* oldPtr = atomic_exchange(&ptr, newPtr);
if (oldPtr) delete oldPtr;
}
};
#endif // UTILS_H