Qx v0.6
Qt Extensions Library
Loading...
Searching...
No Matches
qx-threadsafesingleton.h
1#ifndef QX_THREAD_SAFE_SINGLETON_H
2#define QX_THREAD_SAFE_SINGLETON_H
3
4// Qt Includes
5#include <QMutex>
6#include <QRecursiveMutex>
7
8// Intra-component Includes
9#include "qx/core/qx-exclusiveaccess.h"
10
11// Extra-component Includes
13
14namespace Qx
15{
16
17template<class Singleton, typename Mutex = QMutex>
18 requires any_of<Mutex, QMutex, QRecursiveMutex>
20{
21//-Class Members---------------------------------------------------------------------------------------------
22private:
23 // Needs to be static so it can be locked before the the singleton is created, or else a race in instance() could occur.
24 static inline constinit Mutex smMutex;
25
26//-Constructor----------------------------------------------------------------------------------------------
27protected:
29
30//-Class Functions----------------------------------------------------------------------------------------------
31public:
33 {
34 static Singleton s;
35 return Qx::ExclusiveAccess(&s, &smMutex); // Provides locked access to singleton, that unlocks when destroyed
36 }
37};
38
39}
40
41//-Macros----------------------------------------------------------------------------------------------------------
42// Macro to be used in all derivatives
43#define QX_THREAD_SAFE_SINGLETON(...) friend ThreadSafeSingleton<__VA_ARGS__>
44
45#endif // QX_THREAD_SAFE_SINGLETON_H
The ExclusiveAccess template class is a convenience class that simplifies access to resources secured...
Definition qx-exclusiveaccess.h:16
The ThreadSafeSingleton template class provides access to a static singleton instance in a thread-saf...
Definition qx-threadsafesingleton.h:20
static Qx::ExclusiveAccess< Singleton, QMutex > instance()
Definition qx-threadsafesingleton.h:32
The Qx namespace is the main namespace through which all non-global functionality of the Qx library i...
Definition qx-abstracterror.cpp:13
The qx-concepts header file provides a library of general purpose concepts as an extension of the sta...