#include
#include
#include
std::mutex gmutex;
using namespace std;
template
class Singleton
{
public:
static Type* GetSingleton()
{
if (siglen == NULL)
{
unique_lock lock(gmutex);//C++11加鎖。
if (siglen == NULL)
{
siglen = new Type();
Type *temp = new Type();
MemoryBarrier();
siglen = temp;
}
}
return siglen;
}
private:
static Type* siglen;
};
template
Type* Singleton::siglen = NULL;
class Text
{
public:
Text()
{
data = 100;
//因為是單例模式,所以唯一會出現申請內存,調用構造
//函數,賦值三個步驟混亂的機會只有在前面的1-2次
//的時候,可惜速度太快了,這種情況發生的概率及其低
//,但是我們的心理要始終明白。
}
void Printf()
{
cout << data=<::GetSingleton()->Printf();
return DWORD(0);
}
private:
int data;
};
int main()
{
HANDLE hThread;
DWORD threadId;
for (int i = 0; i < 10; i++)
{
hThread = CreateThread(NULL, 0, &(Text::ThreadFunc), (void *)123,0, &threadId);
}
Sleep(5);
cout << ThreadFunc is running!!! << endl;
return 0;
}
#include
using namespace std;
//引用計數的智能指針。
template
class my_auto_ptr
{
public:
my_auto_ptr(Type* p = NULL) :ptr(p)
{
count = new int[1];
count[0] = 1;
}
my_auto_ptr(const my_auto_ptr &ma)
{
count = ma.count;
count[0]++;
}
my_auto_ptr& operator=(const my_auto_ptr &ma)
{
if (this != &ma)
{
this->~my_auto_ptr();
count = ma.count;
count[0]++;
ptr = ma.ptr;
}
return *this;
}
~my_auto_ptr()
{
if (count!=NULL &&count[0]-- == 1)
{
cout << ~my_auto_ptr() << endl;
delete ptr;
ptr = NULL;
delete[] count;
count = NULL;
}
}
Type* operator->()
{
return ptr;
}
Type& operator*()
{
return *ptr;
}
private:
Type *ptr;
int *count;
};
int main()
{
my_auto_ptr ps(new int(100));
my_auto_ptr pb(ps);
my_auto_ptr pd;
pd = pb;
return 0;
}