好记性,不如烂笔头。对于单例模式的理解和应用还是需要多多实践,这次有感而发,写份基于线程运行的单例模式。
单例模式该怎样去实现:构造函数声明为private或protect防止被外部函数实例化,内部保存一个private static的类指针保存唯一的实例,实例的动作由一个public的类方法代劳,该方法也返回单例类唯一的实例。
头文件:
#pragma once
#include <Windows.h>
#include <vector>
class CMyThread
{
public:
CMyThread(){};
virtual ~CMyThread(){};
virtual void DoThread()
{
printf("****\n");
};
};
class CThreadFunNode
{
public:
CMyThread* m_pThread;
CThreadFunNode()
{
m_pThread = NULL;
};
~CThreadFunNode(){};
};
class CThreadFunList
{
public:
CThreadFunList(){};
~CThreadFunList()
{
std::vector<CThreadFunNode*>::iterator it = m_FunList.begin();
for (; it != m_FunList.end(); ++it)
{
CThreadFunNode* pNode = (*it);
delete pNode;
pNode = NULL;
}
m_FunList.clear();
};
void AddFun(CMyThread* v_pThread)
{
CThreadFunNode* pNode = new CThreadFunNode;
if (pNode)
{
pNode->m_pThread = v_pThread;
m_FunList.push_back(pNode);
}
};
void Excute()
{
std::vector<CThreadFunNode*>::iterator it = m_FunList.begin();
for (; it != m_FunList.end(); ++it)
{
CThreadFunNode* pNode = (*it);
pNode->m_pThread->DoThread();
}
}
private:
std::vector<CThreadFunNode*> m_FunList;
};
class CThreadObject
{
public:
~CThreadObject();
void Start();
void Stop();
void AddFun(CMyThread* v_pThread);
void ThreadProc();
static CThreadObject* GetInstance();
static void Release();
private:
CThreadObject();
static CThreadObject* m_pThreadObject;
CThreadFunList m_FunList;
HANDLE m_hThread;
BOOL m_bThreadCanRun;
};
源文件:
#include "stdafx.h"
#include "MyThread.h"
DWORD WINAPI GlobalProc(LPVOID v_lpParam)
{
CThreadObject* pObject = (CThreadObject*)v_lpParam;
pObject->ThreadProc();
return 0;
}
CThreadObject* CThreadObject::m_pThreadObject = NULL;
CThreadObject::CThreadObject()
{
m_bThreadCanRun = FALSE;
DWORD dwThread = 0;
m_hThread = CreateThread(NULL, 0, GlobalProc, this, 0, &dwThread);
}
CThreadObject::~CThreadObject()
{
m_bThreadCanRun = FALSE;
if (m_hThread)
{
if (WAIT_OBJECT_0 != WaitForSingleObject(m_hThread, 100L))
{
TerminateThread(m_hThread, 0);
}
CloseHandle(m_hThread);
}
}
void CThreadObject::AddFun( CMyThread* v_pThread )
{
m_FunList.AddFun(v_pThread);
}
void CThreadObject::ThreadProc()
{
while(TRUE)
{
if (m_bThreadCanRun)
{
m_FunList.Excute();
}
}
}
void CThreadObject::Start()
{
m_bThreadCanRun = TRUE;
}
void CThreadObject::Stop()
{
m_bThreadCanRun = FALSE;
}
CThreadObject* CThreadObject::GetInstance()
{
if (NULL == m_pThreadObject)
{
m_pThreadObject = new CThreadObject;
}
return m_pThreadObject;
}
void CThreadObject::Release()
{
if(NULL != m_pThreadObject)
{
delete m_pThreadObject;
m_pThreadObject = NULL;
}
}
应用方法:
#include "stdafx.h"
#include "MyThread.h"
class CTestThread : public CMyThread
{
public:
CTestThread(){};
~CTestThread(){};
void DoThread()
{
printf("###\n");
};
};
int _tmain(int argc, _TCHAR* argv[])
{
CTestThread TestThread;
CThreadObject* pThreadObject = CThreadObject::GetInstance();
pThreadObject->AddFun(&TestThread);
pThreadObject->Start();
Sleep(100);
pThreadObject->Stop();
pThreadObject->Release();
system("pause");
return 0;
}