-
Notifications
You must be signed in to change notification settings - Fork 0
/
mutex8.cpp
41 lines (33 loc) · 939 Bytes
/
mutex8.cpp
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
#include <iostream>
#include <thread>
#include <chrono>
#include <mutex>
using namespace std;
mutex myMutex;
class MySingleton {
public:
static MySingleton& getInstance() {
// This to make the singleton thread safe
lock_guard<mutex> myLock(myMutex);
if (!instance) instance = new MySingleton();
return *instance;
}
private:
MySingleton();
~MySingleton();
//No copy operator
MySingleton(const MySingleton&) = delete;
MySingleton& operator= (const MySingleton&) = delete;
static MySingleton* instance;
};
int main() {
/*
Problem: Each time I use my singleton in one of the below ways, it will lock the mutex which is slow, especially if I just read from it.
MySingleton::MySingleton()= default;
MySingleton::~MySingleton()= default;
MySingleton* MySingleton::instance= nullptr;
...
MySingleton::getInstance();
*/
return 0;
}