#include<iostream>
#include<thread>
#include<mutex>
#include<string>
using namespace std;
class Log;
static Log*lg = nullptr;
static once_flag once;
class Log {
public:
Log() {};
Log(const Log& log) = delete;
Log& operator=(const Log& log) = delete;
static Log& GetInstance() {
call_once(once, init);//保证多线程的情况下只有一个线程执行
return *lg;
}
static void init() {
if (!lg) lg=new Log;
}
void PrintLog(string msg) {
cout <<__TIME__<<" "<< msg << endl;
}
};
void print_error() {
Log::GetInstance().PrintLog("error");
}
int main() {
thread t1(print_error);
thread t2(print_error);
t1.join();
t2.join();
return 0;
}
多线程之call_once与其使用场景
最新推荐文章于 2024-08-10 00:11:49 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)