#include <iostream>
#include <thread>
#include <vector>
#include <list>
#include <mutex>
using namespace std;
class MySigleton {
public:
// 借用call_once()创建单例对象
static void CreateInstance() {
instance = new MySigleton();
static CGarHuishou c1; //定义为静态,保证该函数执行完不被析构
}
static MySigleton* getInstance() {
//方法一:手动创建多线程单例对象
//if (instance == NULL) {
// unique_lock<mutex> myULock(resourceMutex);
// if (instance == NULL) {
// instance = new MySigleton();
// static CGarHuishou c1; //定义为静态,保证该函数执行完不被析构
// }
//}
// 方法二:使用call_once()函数创建单例对象
call_once(flag, CreateInstance);
return instance;
}
~MySigleton() {
cout << "单例类析构函数" << endl;
}
//垃圾回收
class CGarHuishou {
public:
~CGarHuishou() {
cout << "执行垃圾回收" << endl;
if (instance) {
delete instance;
instance =
C++ 创建多线程单例对象
最新推荐文章于 2023-04-07 16:05:29 发布