240717班级,工业化控制系统,煤矿相关行业,昆仑系统
123
wangky
2024-10-28 38a299bb8f447b3e54dde0aa91ebcc205b4aebf0
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
#include <iostream>
#include <mutex>
#include <fstream>
#include <string>
#include <ctime>
using namespace std;
class A {
private:
    ofstream logFile;
    A() {
        logFile.open("123.txt", ios::app);
    }
    ~A() {
        logFile.close();
    }
    A(const A &t){}
    A& operator=(const A &t){}
    static A* volatile s_obj;
    static mutex g_mutex;
public:
    static A* getInstance() {
        if (s_obj == nullptr) {
            lock_guard<mutex> guard(g_mutex);
            if (s_obj == nullptr) {
                s_obj = new A;
            }
        }
        return s_obj;
    }
    void write(const string& level, const string& description, const string& time) {
        logFile << "[" << level << "] " << "[" << time << "] " << description << endl;
    }
    void release() {
        if (s_obj) {
            delete s_obj;
            s_obj = nullptr;
        }
    }
};
 
A* volatile A::s_obj = nullptr;
mutex A::g_mutex;
 
int main() {
    A* a1 = A::getInstance();
    A* a2 = A::getInstance();
    if (a1 == a2) {
        cout << "单例成功" << endl;
    }
    else {
        cout << "单例失败" << endl;
    }
    time_t now = time(nullptr);
    char buffer[80];
    struct tm timeinfo;
    localtime_s(&timeinfo, &now);
    strftime(buffer, 80, "%Y - %m - %d %H:%M:%S", &timeinfo);
    string timeStr(buffer);
    a1->write("1", "日志", timeStr);
    a1->release();
    return 0;
}