123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124 |
- #include "stdafx.h"
- #include <process.h>
- #include "Thread.h"
- #ifdef _DEBUG
- #define new DEBUG_NEW
- #undef THIS_FILE
- static char THIS_FILE[] = __FILE__;
- #endif
- unsigned int WINAPI ThreadProc(IN LPVOID lpParam);
- CThreadBase::CThreadBase()
- {
- m_nIndex = -1;
- m_hThread = NULL;
- m_ThreadStatus = THREADSTATUS_STOP;
- m_nThreadID = 0;
- m_hExit = NULL;
- m_hSemaphore = NULL;
- m_nSemaphoreNum = MAX_SEMAPHONE_NUM;
- }
- CThreadBase::~CThreadBase()
- {
-
- }
- /************************************************************************/
- /*
- 函数:Start
- 描述:启动线程
- 参数:
- 返回:1成功, 0失败
- */
- /************************************************************************/
- int CThreadBase::Start()
- {
- if(m_ThreadStatus != THREADSTATUS_STOP)
- return 1;
- m_hExit = CreateEvent(NULL, FALSE, FALSE, NULL);
- m_hSemaphore = CreateSemaphore(NULL, 0, MAX_SEMAPHONE_NUM, NULL);
-
- if(m_hThread == NULL)
- m_hThread = (HANDLE)_beginthreadex(NULL, 0, ThreadProc, this, 0, &m_nThreadID);
- if(m_hThread == 0)
- {
- CString strError = _T("");
- strError.Format(_T("创建线程失败:%d\n"), ::GetLastError());
- OutputDebugString(strError);
- return 0;
- }
- m_ThreadStatus = THREADSTATUS_WAIT;
- return 1;
- }
- void CThreadBase::Exit()
- {
- if(m_hExit)
- SetEvent(m_hExit);
- WakeUp();
- if(m_hThread)
- {
- #ifdef _DEBUG
- CString strMsg = _T("");
- strMsg.Format(_T("线程%d 等待退出\n"), m_nThreadID);
- OutputDebugString(strMsg);
- WaitForSingleObject(m_hThread, INFINITE);
- strMsg.Format(_T("线程%d 退出\n"), m_nThreadID);
- OutputDebugString(strMsg);
- #else
- WaitForSingleObject(m_hThread, INFINITE);
- #endif //#ifdef _DEBUG
- CloseHandle(m_hThread);
- }
- m_hThread = NULL;
- if(m_hSemaphore)
- CloseHandle(m_hSemaphore);
- m_hSemaphore = NULL;
- if(m_hExit)
- CloseHandle(m_hExit);
- m_hExit = NULL;
- }
- /************************************************************************/
- /*
- 函数:WakeUp
- 描述:唤醒
- 参数:
- 返回:1成功,0失败
- */
- /************************************************************************/
- void CThreadBase::WakeUp()
- {
- if(m_hSemaphore)
- ReleaseSemaphore(m_hSemaphore, 1, NULL);
- }
- /************************************************************************/
- /*
- 函数:WorkItem
- 描述:工作项
- 参数:
- IN LPVOID lpParam
- 返回:0
- */
- /************************************************************************/
- unsigned int WINAPI ThreadProc(IN LPVOID lpParam)
- {
- CThreadBase* p = (CThreadBase*)lpParam;
- int nSatus = 0;
- while(1)
- {
- int nSatus = p->Run();
- if(nSatus == THREADSTATUS_EXIT) // 程序结束
- break;
- }
- return 0;
- }
|