經常會遇到需要在類中創建線程,可以使用靜態成員函數,並且將類實例的指針傳入線程函數的方式來實現。
實現代碼代碼如下:
/* 類頭文件 CTestThread.h */
#include<iostream>
#include<process.h>
#include<Windows.h>
class TestThread
{
public:
TestThread();
~TestThread();
int StartThread(); // 開線程
int SetStopFlag(bool flag); //停止線程
private:
static unsigned int WINAPI ThreadFunc(LPVOID lpParam); //線程函數
private:
bool m_bStopFlag;
};
/* 類源文件 CTestThread.cpp */
#include "CTestThread.h"
TestThread::TestThread()
{
m_bStopFlag = false;
}
TestThread::~TestThread()
{
m_bStopFlag = true;
}
int TestThread::StartThread()
{
HANDLE hThread = (HANDLE)_beginthreadex(NULL, 0, &ThreadFunc, (LPVOID)this, 0, NULL);
return 0;
}
int TestThread::SetStopFlag(bool flag)
{
m_bStopFlag = flag;
return 0;
}
unsigned int WINAPI TestThread::ThreadFunc(LPVOID lpParam)
{
TestThread* pthis = (TestThread*)lpParam;
while (!pthis->m_bStopFlag)
{
printf("ThreadFunc is running cassid is %d .\n",pthis->m_classid);
Sleep(1000);
}
printf("ThreadFunc return.\n");
return 0;
}
/* 測試代碼 test.cpp */
#include "CTestThread.h"
int main()
{
TestThread testThread(1);
testThread.StartThread();
char ch;
while (ch = getchar())
{
if (ch == 'q' || ch == 'Q')
{
testThread.SetStopFlag(true);
break;
}
Sleep(1000);
}
}