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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
|
// *****************************************************************************
// * This file is part of the FreeFileSync project. It is distributed under *
// * GNU General Public License: https://www.gnu.org/licenses/gpl-3.0 *
// * Copyright (C) Zenju (zenju AT freefilesync DOT org) - All Rights Reserved *
// *****************************************************************************
#ifndef GLOBALS_H_8013740213748021573485
#define GLOBALS_H_8013740213748021573485
#include <atomic>
#include <memory>
#include <utility>
#include "scope_guard.h"
namespace zen
{
/* Solve static destruction order fiasco by providing shared ownership and serialized access to global variables
=> e.g. accesses to "Global<T>::get()" during process shutdown: _("") used by message in debug_minidump.cpp or by some detached thread assembling an error message!
=> use trivially-destructible POD only!!!
ATTENTION: function-static globals have the compiler generate "magic statics" == compiler-genenerated locking code which will crash or leak memory when accessed after global is "dead"
=> "solved" by FunStatGlobal, but we can't have "too many" of these... */
class PodSpinMutex
{
public:
bool tryLock();
void lock();
void unlock();
bool isLocked();
private:
std::atomic_flag flag_{}; /* => avoid potential contention with worker thread during Global<> construction!
- "For an atomic_flag with static storage duration, this guarantees static initialization:" => just what the doctor ordered!
- "[default initialization] initializes std::atomic_flag to clear state" - since C++20 =>
- "std::atomic_flag is [...] guaranteed to be lock-free"
- interestingly, is_trivially_constructible_v<> is false, thanks to constexpr! https://developercommunity.visualstudio.com/content/problem/416343/stdatomic-no-longer-is-trivially-constructible.html */
};
#define GLOBAL_RUN_ONCE(X) \
struct ZEN_CONCAT(GlobalInitializer, __LINE__) \
{ \
ZEN_CONCAT(GlobalInitializer, __LINE__)() { X; } \
} ZEN_CONCAT(globalInitializer, __LINE__)
template <class T>
class Global //don't use for function-scope statics!
{
public:
consteval Global() {}; //demand static zero-initialization!
~Global()
{
static_assert(std::is_trivially_destructible_v<Pod>, "this memory needs to live forever");
pod_.spinLock.lock();
std::shared_ptr<T>* oldInst = std::exchange(pod_.inst, nullptr);
pod_.destroyed = true;
pod_.spinLock.unlock();
delete oldInst;
}
std::shared_ptr<T> get() //=> return std::shared_ptr to let instance life time be handled by caller (MT usage!)
{
pod_.spinLock.lock();
ZEN_ON_SCOPE_EXIT(pod_.spinLock.unlock());
if (pod_.inst)
return *pod_.inst;
return nullptr;
}
void set(std::unique_ptr<T>&& newInst)
{
std::shared_ptr<T>* tmpInst = nullptr;
if (newInst)
tmpInst = new std::shared_ptr<T>(std::move(newInst));
{
pod_.spinLock.lock();
ZEN_ON_SCOPE_EXIT(pod_.spinLock.unlock());
if (!pod_.destroyed)
std::swap(pod_.inst, tmpInst);
else
assert(false);
}
delete tmpInst;
}
bool wasDestroyed()
{
pod_.spinLock.lock();
ZEN_ON_SCOPE_EXIT(pod_.spinLock.unlock());
return pod_.destroyed;
}
private:
struct Pod
{
PodSpinMutex spinLock; //rely entirely on static zero-initialization! => avoid potential contention with worker thread during Global<> construction!
//serialize access: can't use std::mutex: has non-trival destructor
std::shared_ptr<T>* inst = nullptr;
bool destroyed = false;
} pod_;
};
//===================================================================================================================
//===================================================================================================================
struct CleanUpEntry
{
using CleanUpFunction = void (*)(void* callbackData);
CleanUpFunction cleanUpFun = nullptr;
void* callbackData = nullptr;
CleanUpEntry* prev = nullptr;
};
void registerGlobalForDestruction(CleanUpEntry& entry);
template <class T>
class FunStatGlobal
{
public:
consteval FunStatGlobal() {}; //demand static zero-initialization!
//No ~FunStatGlobal()!
void initOnce(std::unique_ptr<T> (*getInitialValue)())
{
static_assert(std::is_trivially_destructible_v<FunStatGlobal>, "this class must not generate code for magic statics!");
pod_.spinLock.lock();
ZEN_ON_SCOPE_EXIT(pod_.spinLock.unlock());
if (!pod_.cleanUpEntry.cleanUpFun)
{
assert(!pod_.inst);
if (std::unique_ptr<T> newInst = (*getInitialValue)())
pod_.inst = new std::shared_ptr<T>(std::move(newInst));
registerDestruction();
}
}
std::shared_ptr<T> get()
{
pod_.spinLock.lock();
ZEN_ON_SCOPE_EXIT(pod_.spinLock.unlock());
if (pod_.inst)
return *pod_.inst;
return nullptr;
}
void set(std::unique_ptr<T>&& newInst)
{
std::shared_ptr<T>* tmpInst = nullptr;
if (newInst)
tmpInst = new std::shared_ptr<T>(std::move(newInst));
{
pod_.spinLock.lock();
ZEN_ON_SCOPE_EXIT(pod_.spinLock.unlock());
std::swap(pod_.inst, tmpInst);
registerDestruction();
}
delete tmpInst;
}
private:
//call while holding pod_.spinLock
void registerDestruction()
{
assert(pod_.spinLock.isLocked());
if (!pod_.cleanUpEntry.cleanUpFun)
{
pod_.cleanUpEntry.callbackData = this;
pod_.cleanUpEntry.cleanUpFun = [](void* callbackData)
{
auto thisPtr = static_cast<FunStatGlobal*>(callbackData);
thisPtr->set(nullptr);
};
registerGlobalForDestruction(pod_.cleanUpEntry);
}
}
struct Pod
{
PodSpinMutex spinLock; //rely entirely on static zero-initialization! => avoid potential contention with worker thread during Global<> construction!
//serialize access; can't use std::mutex: has non-trival destructor
std::shared_ptr<T>* inst = nullptr;
CleanUpEntry cleanUpEntry;
} pod_;
};
inline
void registerGlobalForDestruction(CleanUpEntry& entry)
{
static struct
{
PodSpinMutex spinLock;
CleanUpEntry* head = nullptr;
} cleanUpList;
static_assert(std::is_trivially_destructible_v<decltype(cleanUpList)>, "we must not generate code for magic statics!");
cleanUpList.spinLock.lock();
ZEN_ON_SCOPE_EXIT(cleanUpList.spinLock.unlock());
std::atexit([]
{
cleanUpList.spinLock.lock();
ZEN_ON_SCOPE_EXIT(cleanUpList.spinLock.unlock());
(*cleanUpList.head->cleanUpFun)(cleanUpList.head->callbackData);
cleanUpList.head = cleanUpList.head->prev; //nicely clean up in reverse order of construction
});
entry.prev = cleanUpList.head;
cleanUpList.head = &entry;
}
//------------------------------------------------------------------------------------------
inline
bool PodSpinMutex::tryLock()
{
return !flag_.test_and_set(std::memory_order_acquire);
}
inline
void PodSpinMutex::lock()
{
while (!tryLock())
flag_.wait(true, std::memory_order_relaxed);
}
inline
void PodSpinMutex::unlock()
{
flag_.clear(std::memory_order_release);
flag_.notify_one();
}
inline
bool PodSpinMutex::isLocked()
{
if (!tryLock())
return true;
unlock();
return false;
}
}
#endif //GLOBALS_H_8013740213748021573485
|