-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsingleton.cpp
68 lines (55 loc) · 1.96 KB
/
singleton.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
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
// {"category": "C++11", "notes": "Thread-safe singleton"}
#include <SDKDDKVer.h>
#include <stdio.h>
#include <tchar.h>
#include <iostream>
#include <Windows.h>
using namespace std;
//------------------------------------------------------------------------------
//
// http://www.nuonsoft.com/blog/2017/08/10/implementing-a-thread-safe-singleton-with-c11-using-magic-statics/
//
//------------------------------------------------------------------------------
class CSingleton final
{
public:
static CSingleton& GetInstance();
private:
CSingleton() = default;
~CSingleton() = default;
CSingleton(const CSingleton&) = delete;
CSingleton& operator=(const CSingleton&) = delete;
CSingleton(CSingleton&&) = delete;
CSingleton& operator=(CSingleton&&) = delete;
};
CSingleton& CSingleton::GetInstance()
{
static CSingleton instance; // C++11 guarantees that this will be initialized in a thread-safe way.
return instance;
}
//------------------------------------------------------------------------------
//
// Demo execution
//
//------------------------------------------------------------------------------
int _tmain(int argc, _TCHAR* argv[])
{
CSingleton* workerInstance = nullptr;
DWORD workerThreadId = 0;
HANDLE thread = CreateThread(nullptr, 0, [](LPVOID pWorkerInstance) -> DWORD
{
*static_cast<LPVOID*>(pWorkerInstance) = &CSingleton::GetInstance();
return ERROR_SUCCESS;
}, &workerInstance, 0, &workerThreadId);
CSingleton* primaryInstance = &CSingleton::GetInstance();
DWORD primaryThreadId = GetCurrentThreadId();
if (thread != NULL)
{
WaitForSingleObject(thread, INFINITE);
CloseHandle(thread);
}
cout << "GetInstance: " << workerInstance << " (tid: " << workerThreadId << ")" << endl;
cout << "GetInstance: " << primaryInstance << " (tid: " << primaryThreadId << ")" << endl;
cout << (workerInstance == primaryInstance ? "PASS" : "FAIL") << endl;
return 0;
}