📄 daemonthread.h
字号:
#ifndef _DAEMON_THREAD_H_
#define _DAEMON_THREAD_H_
#include <vector>
using namespace std;
//线程句柄
typedef struct _daemon_thread_handle{
HANDLE hThread; //线程句柄
HANDLE hEvent; //事件句柄
}DAEMON_THREAD_HANDLE;
//线程参数
typedef struct _daemon_thread_param{
LPVOID pParam; //参数
HANDLE hEvent; //事件
}DAEMON_THREAD_PARAM;
//线程类
class CDaemonThread
{
public:
CDaemonThread() {};
~CDaemonThread() {};
public:
//启动线程
//参数:lpStartAddress(in) - 线程函数。
// pParam(in) - 线程参数。
//返回值:INVALID_HANDLE_VALUE - 出错 其它 - 线程句柄。
HANDLE StartThread(LPTHREAD_START_ROUTINE lpStartAddress,LPVOID pParam)
{
DAEMON_THREAD_HANDLE handle;
handle.hEvent = ::CreateEvent(NULL,FALSE,FALSE,NULL);
if (handle.hEvent == NULL)
return INVALID_HANDLE_VALUE;
memset(&m_threadParam,0,sizeof(m_threadParam));
m_threadParam.pParam = pParam;
m_threadParam.hEvent = handle.hEvent;
handle.hThread = ::CreateThread(NULL,0,lpStartAddress,(LPVOID)&m_threadParam,0,NULL);
if (handle.hThread == NULL)
{
CloseHandle(handle.hEvent);
return INVALID_HANDLE_VALUE;
}
m_listThreads.push_back(handle);
return handle.hThread;
}
//停止线程
//参数:hThread(in) - 线程句柄。
// timeout(in) - 超时时间。
int StopThread(HANDLE hThread,DWORD timeout)
{
for (vector<DAEMON_THREAD_HANDLE>::iterator it = m_listThreads.begin(); it != m_listThreads.end(); it++)
{
if (it->hThread == hThread)
{
::SetEvent(it->hEvent);
if (::WaitForSingleObject(it->hThread,timeout) != WAIT_OBJECT_0)
::TerminateThread(it->hThread,0);
m_listThreads.erase(it);
return 0;
}
}
return -1;
}
//停止线程
void StopThread(DWORD timeout = 500)
{
while(!m_listThreads.empty())
{
StopThread(m_listThreads.rbegin()->hThread,timeout);
CloseHandle(m_listThreads.rbegin()->hEvent);
}
}
void SuspendThread()
{
::SuspendThread(m_listThreads.rbegin()->hThread);
}
void ResumeThread()
{
::ResumeThread(m_listThreads.rbegin()->hThread);
}
private:
vector<DAEMON_THREAD_HANDLE> m_listThreads; //线程队列
DAEMON_THREAD_PARAM m_threadParam; //线程参数
};
#endif
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -