C++クラスでのスレッドの作成

1647 ワード

クラスにスレッドを作成する必要がある場合がよくあります.静的メンバー関数を使用し、クラスインスタンスのポインタをスレッド関数に転送する方法で実装できます.
実装コードは次のとおりです.
/*      CTestThread.h */
#include
#include
#include

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 .
",pthis->m_classid); Sleep(1000); } printf("ThreadFunc return.
"); 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);
    }
}