-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSingleton.hpp
More file actions
36 lines (29 loc) · 727 Bytes
/
Singleton.hpp
File metadata and controls
36 lines (29 loc) · 727 Bytes
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
// Double-checked locking
#ifndef SINGLETON_H
#define SINGLETON_H
#include <mutex>
class Singleton {
public:
volatile static Singleton* getInstance();
private:
Singleton () = default;
volatile static Singleton *uniqueInstance;
static std::mutex uniqueInstance_mtx; // protect uniqueInstance
};
inline
volatile
Singleton* Singleton::uniqueInstance = nullptr;
inline
std::mutex Singleton::uniqueInstance_mtx; // protect uniqueInstance
inline
volatile Singleton*
Singleton::getInstance()
{
if (uniqueInstance == nullptr) {
std::lock_guard<std::mutex> gaurd(uniqueInstance_mtx); // lock
if (uniqueInstance == nullptr)
uniqueInstance = new Singleton();
}
return uniqueInstance;
}
#endif /* SINGLETON_H */