您的位置:首页 > 编程语言 > C语言/C++

C++ 线程-类方式

2017-01-24 00:10 471 查看
#include <iostream>
using namespace std;

#include <windows.h>
#include <process.h>

class App
{
public:
App() : m_bRunning(false), m_hThread(NULL)
{
}

virtual ~App()
{
}

bool Start()
{
if (!m_bRunning)
{
m_bRunning = true;
m_hThread = (HANDLE)_beginthreadex(NULL, 0, &ThreadFunc, this, 0, 0);
}
return m_bRunning;
}

bool Stop()
{
if (m_bRunning)
{
m_bRunning = false;                      // 通知线程退出
WaitForSingleObject(m_hThread, INFINITE);// 等待线程退出
CloseHandle(m_hThread);                  // 关闭线程句柄
m_hThread = NULL;
}
return true;
}

private:
void DoTask()
{
while (m_bRunning)
{
// 线程任务开始
// ...
}
}

static unsigned __stdcall ThreadFunc(void* pArguments)
{
App* app = reinterpret_cast<App*>(pArguments);
app->DoTask();  // 线程开始
_endthreadex(0);// 中止线程
return 0;
}

private:
bool	m_bRunning;
HANDLE	m_hThread;
};

int _tmain(int argc, _TCHAR* argv[])
{
App app;
app.Start();

// …

//app.Stop();

system("pause");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: