forked from Light-City/CPlusPlusThings
-
Notifications
You must be signed in to change notification settings - Fork 0
/
barrier_singleton.cpp
46 lines (38 loc) · 886 Bytes
/
barrier_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
//
// Created by light on 20-2-7.
//
#include <iostream>
using namespace std;
#include <mutex>
#define barrier() __asm__ volatile ("lwsync")
// method 1 operator new + placement new
//singleton *instance() {
// if (p == nullptr) {
// lock_guard<mutex> guard(lock_);
// if (p == nullptr) {
// singleton *tmp = static_cast<singleton *>(operator new(sizeof(singleton)));
// new(p)singleton();
// p = tmp;
// }
// }
// return p;
//}
class singleton {
private:
singleton() {}
static singleton *p;
static mutex lock_;
public:
static singleton *instance();
};
singleton *singleton::p = nullptr;
singleton *singleton::instance() {
if (p == nullptr) {
lock_guard<mutex> guard(lock_);
barrier();
if (p == nullptr) {
p = new singleton();
}
}
return p;
}