示例中使用模板创建单例对象,实际操作过程中换成具体类中实现。注意要求单例模式的类要把构造隐藏。
#include <iostream>
#include <mutex>
using namespace std;
mutex g_single_mutex;
#define sync(action) g_single_mutex.lock(); action; g_single_mutex.unlock();
class testInstance
{
public:
void print(int val)
{
cout << val << endl;
}
};
template<class TTtype>
class SingleObjMode
{
public:
static TTtype* instance();
static mutex m_mutex;
protected:
SingleObjMode() {}
static TTtype* m_instance;
};
template<class TTtype>
TTtype* SingleObjMode<TTtype>::m_instance = nullptr;
template<class TTtype>
mutex SingleObjMode<TTtype>::m_mutex;
template<class TTtype>
TTtype* SingleObjMode<TTtype>::instance()
{
if (m_instance == nullptr) // 避免每次进入函数都加锁
{
m_mutex.lock();
if (m_instance == nullptr)
{
TTtype* obj = new TTtype();
cout << "create obj" << endl;
m_instance = obj;
}
m_mutex.unlock();
}
return m_instance;
}
void singleModefunc(int val)
{
testInstance *obj = SingleObjMode<testInstance>::instance();
sync(obj->print(val))
}
void singleModeTest()
{
vector<std::thread> vecThread;
for (int i = 0; i < 100; ++i)
{
vecThread.push_back(std::thread(singleModefunc, i + 1));
}
for (int i = 0; i < vecThread.size(); ++i)
{
vecThread[i].join();
}
}
int main()
{
singleModeTest();
}