简介本文向大家介绍如何C++将线程封装成类方式,具有一定的C++实战价值,感兴趣的朋友可以参考一下。

代码

#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)
		{
			// 线程任务开始
			// ...
			cout << "C++实战网(www.cppszw.com)" << endl;
		}
	}

	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;
}


更多为你推荐