File: Singleton.hh

package info (click to toggle)
ptl 2.3.3-2.1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,296 kB
  • sloc: cpp: 8,195; python: 246; sh: 7; makefile: 3
file content (405 lines) | stat: -rw-r--r-- 11,913 bytes parent folder | download | duplicates (4)
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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
// MIT License
//
// Copyright (c) 2020 Jonathan R. Madsen
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
//

#pragma once

#include <atomic>
#include <functional>
#include <memory>
#include <mutex>
#include <set>
#include <thread>
#include <type_traits>

namespace PTL
{
/// \class PTL::Singleton
/// \brief Singleton object that allows a deleter class to be specified
///
template <typename Type,
          typename PointerT = std::unique_ptr<Type, std::default_delete<Type>>>
class Singleton
{
public:
    using this_type     = Singleton<Type, PointerT>;
    using thread_id_t   = std::thread::id;
    using mutex_t       = std::recursive_mutex;
    using auto_lock_t   = std::unique_lock<mutex_t>;
    using pointer       = Type*;
    using list_t        = std::set<pointer>;
    using smart_pointer = PointerT;
    using deleter_t     = std::function<void(PointerT&)>;

    template <bool B, typename T = int>
    using enable_if_t = typename std::enable_if<B, T>::type;

public:
    // Constructor and Destructors
    Singleton();
    Singleton(pointer);
    ~Singleton();

    Singleton(const Singleton&) = delete;
    Singleton(Singleton&&)      = delete;
    Singleton& operator=(const Singleton&) = delete;
    Singleton& operator=(Singleton&&) = delete;

public:
    // public static functions
    static pointer     GetInstance();
    static pointer     GetMasterInstance();
    static thread_id_t GetMasterThreadID() { return f_master_thread(); }
    static list_t      Children() { return f_children(); }
    static bool        IsMaster(pointer ptr) { return ptr == GetRawMasterInstance(); }
    static bool        IsMasterThread();
    static void        Insert(pointer);
    static void        Remove(pointer);
    static mutex_t&    GetMutex() { return f_mutex(); }

public:
    // public member function
    void Initialize();
    void Initialize(pointer);
    void Destroy();
    void Reset(pointer);
    void Reset();

    // since we are overloading delete we overload new
    void* operator new(size_t)
    {
        this_type* ptr = ::new this_type();
        return static_cast<void*>(ptr);
    }

    // overload delete so that f_master_instance is guaranteed to be
    // a nullptr after deletion
    void operator delete(void* ptr)
    {
        this_type* _instance = (this_type*) (ptr);
        ::delete _instance;
        if(std::this_thread::get_id() == f_master_thread())
            f_master_instance() = nullptr;
    }

protected:
    friend class Type;

    // instance functions that do not Initialize
    smart_pointer&        GetSmartInstance() { return _local_instance(); }
    static smart_pointer& GetSmartMasterInstance() { return _master_instance(); }

    // for checking but not allocating
    pointer GetRawInstance()
    {
        return IsMasterThread() ? f_master_instance() : _local_instance().get();
    }
    static pointer GetRawMasterInstance() { return f_master_instance(); }

private:
    // Private functions
    static smart_pointer& _local_instance()
    {
        static thread_local smart_pointer _instance = smart_pointer();
        return _instance;
    }

    static smart_pointer& _master_instance()
    {
        static smart_pointer _instance = smart_pointer();
        return _instance;
    }

    void* operator new[](std::size_t) noexcept { return nullptr; }
    void  operator delete[](void*) noexcept {}

    template <typename Tp = Type, typename PtrT = PointerT,
              enable_if_t<(std::is_same<PtrT, std::shared_ptr<Tp>>::value)> = 0>
    deleter_t& GetDeleter()
    {
        static deleter_t _instance = [](PointerT&) {};
        return _instance;
    }

    template <typename Tp = Type, typename PtrT = PointerT,
              enable_if_t<!(std::is_same<PtrT, std::shared_ptr<Tp>>::value)> = 0>
    deleter_t& GetDeleter()
    {
        static deleter_t _instance = [](PointerT& _master) {
            auto& del = _master.get_deleter();
            del(_master.get());
            _master.reset(nullptr);
        };
        return _instance;
    }

private:
    // Private variables
    struct persistent_data
    {
        thread_id_t m_master_thread = std::this_thread::get_id();
        mutex_t     m_mutex;
        pointer     m_master_instance = nullptr;
        list_t      m_children        = {};

        persistent_data()                       = default;
        ~persistent_data()                      = default;
        persistent_data(const persistent_data&) = delete;
        persistent_data(persistent_data&&)      = delete;
        persistent_data& operator=(const persistent_data&) = delete;
        persistent_data& operator=(persistent_data&&) = delete;

        persistent_data(pointer _master, std::thread::id _tid)
        : m_master_thread(_tid)
        , m_master_instance(_master)
        {}

        void reset()
        {
            m_master_instance = nullptr;
            m_children.clear();
        }
    };

    bool                m_IsMaster = false;
    static thread_id_t& f_master_thread();
    static mutex_t&     f_mutex();
    static pointer&     f_master_instance();
    static list_t&      f_children();

    static persistent_data& f_persistent_data()
    {
        static persistent_data _instance;
        return _instance;
    }
};

//======================================================================================//

template <typename Type, typename PointerT>
typename Singleton<Type, PointerT>::thread_id_t&
Singleton<Type, PointerT>::f_master_thread()
{
    return f_persistent_data().m_master_thread;
}

//--------------------------------------------------------------------------------------//

template <typename Type, typename PointerT>
typename Singleton<Type, PointerT>::pointer&
Singleton<Type, PointerT>::f_master_instance()
{
    return f_persistent_data().m_master_instance;
}

//--------------------------------------------------------------------------------------//

template <typename Type, typename PointerT>
typename Singleton<Type, PointerT>::mutex_t&
Singleton<Type, PointerT>::f_mutex()
{
    return f_persistent_data().m_mutex;
}

//--------------------------------------------------------------------------------------//

template <typename Type, typename PointerT>
typename Singleton<Type, PointerT>::list_t&
Singleton<Type, PointerT>::f_children()
{
    return f_persistent_data().m_children;
}

//--------------------------------------------------------------------------------------//

template <typename Type, typename PointerT>
Singleton<Type, PointerT>::Singleton()
{
    Initialize();
}

//--------------------------------------------------------------------------------------//

template <typename Type, typename PointerT>
Singleton<Type, PointerT>::Singleton(pointer ptr)
{
    Initialize(ptr);
}

//--------------------------------------------------------------------------------------//

template <typename Type, typename PointerT>
Singleton<Type, PointerT>::~Singleton()
{
    auto& del = GetDeleter();
    del(_master_instance());
}

//--------------------------------------------------------------------------------------//

template <typename Type, typename PointerT>
void
Singleton<Type, PointerT>::Initialize()
{
    if(!f_master_instance())
    {
        f_master_thread()   = std::this_thread::get_id();
        f_master_instance() = new Type();
    }
}

//--------------------------------------------------------------------------------------//

template <typename Type, typename PointerT>
void
Singleton<Type, PointerT>::Initialize(pointer ptr)
{
    if(!f_master_instance())
    {
        f_master_thread()   = std::this_thread::get_id();
        f_master_instance() = ptr;
    }
}

//--------------------------------------------------------------------------------------//

template <typename Type, typename PointerT>
void
Singleton<Type, PointerT>::Destroy()
{
    if(std::this_thread::get_id() == f_master_thread() && f_master_instance())
    {
        delete f_master_instance();
        f_master_instance() = nullptr;
    }
    else
    {
        remove(_local_instance().get());
    }
}

//--------------------------------------------------------------------------------------//

template <typename Type, typename PointerT>
typename Singleton<Type, PointerT>::pointer
Singleton<Type, PointerT>::GetInstance()
{
    if(std::this_thread::get_id() == f_master_thread())
        return GetMasterInstance();
    else if(!_local_instance().get())
    {
        _local_instance().reset(new Type());
        Insert(_local_instance().get());
    }
    return _local_instance().get();
}

//--------------------------------------------------------------------------------------//

template <typename Type, typename PointerT>
typename Singleton<Type, PointerT>::pointer
Singleton<Type, PointerT>::GetMasterInstance()
{
    if(!f_master_instance())
    {
        f_master_thread()   = std::this_thread::get_id();
        f_master_instance() = new Type();
    }
    return f_master_instance();
}

//--------------------------------------------------------------------------------------//

template <typename Type, typename PointerT>
void
Singleton<Type, PointerT>::Reset(pointer ptr)
{
    if(IsMaster(ptr))
    {
        if(_master_instance().get())
            _master_instance().reset();
        else if(f_master_instance())
        {
            auto& del = GetDeleter();
            del(_master_instance());
            f_master_instance() = nullptr;
        }
        f_persistent_data().reset();
    }
    else
    {
        _local_instance().reset();
    }
}

//--------------------------------------------------------------------------------------//

template <typename Type, typename PointerT>
void
Singleton<Type, PointerT>::Reset()
{
    if(IsMasterThread())
        _master_instance().reset();
    _local_instance().reset();
    f_persistent_data().reset();
}

//--------------------------------------------------------------------------------------//

template <typename Type, typename PointerT>
bool
Singleton<Type, PointerT>::IsMasterThread()
{
    return std::this_thread::get_id() == f_master_thread();
}

//--------------------------------------------------------------------------------------//

template <typename Type, typename PointerT>
void
Singleton<Type, PointerT>::Insert(pointer itr)
{
    auto_lock_t l(f_mutex());
    f_children().insert(itr);
}

//--------------------------------------------------------------------------------------//

template <typename Type, typename PointerT>
void
Singleton<Type, PointerT>::Remove(pointer itr)
{
    auto_lock_t l(f_mutex());
    for(auto litr = f_children().begin(); litr != f_children().end(); ++litr)
    {
        if(*litr == itr)
        {
            f_children().erase(litr);
            break;
        }
    }
}

//--------------------------------------------------------------------------------------//

}  // namespace PTL