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

一段 C++ 代码(成员函数做线程函数)

2014-07-01 09:07 399 查看
#include 〈windows.h〉
#include 〈conio.h〉
#include 〈stdio.h〉
class CThreadClass
{
public:
typedef DWORD (WINAPI CThreadClass::* pMemberThreadFunc)();
typedef DWORD (WINAPI * PTHREADFUNC)(LPVOID);
    CThreadClass();
    void SetDescrip(char* str) { lstrcpy(m_str,str); }
    void PrintfDescrip() { printf(“m_str = %s\n“,m_str); }
    void RunThread();
    bool FinishThread();
protected:
    char m_str[1024];
    DWORD WINAPI ThreadFunc();
    HANDLE m_ThreadHandle;
    DWORD m_ThreadID;
    pMemberThreadFunc m_pMemberFun;
};
CThreadClass::CThreadClass()
{
    memset(m_str,0,1024);
    m_ThreadID = 0;
    m_ThreadHandle = 0;
    m_pMemberFun = ThreadFunc;
}
void CThreadClass::RunThread()
{
    PTHREADFUNC pFun;
    DWORD dwAddress;
    memcpy(&dwAddress,&m_pMemberFun,sizeof(m_pMemberFun));
    memcpy(&pFun, &dwAddress, sizeof(pFun));
    m_ThreadHandle = CreateThread(NULL, 0, pFun, this, 0, &m_ThreadID);
}
bool CThreadClass::FinishThread()
{
    bool bRet = true;
    if (m_ThreadID == NULL)
        return bRet;
    ::PostThreadMessage(m_ThreadID, WM_QUIT, 0, 0);
    DWORD rc = ::WaitForSingleObject(m_ThreadHandle, 5000);
    if(rc == WAIT_TIMEOUT)
    {
        TerminateThread(m_ThreadHandle,0);
        bRet = false;
    }
    if (m_ThreadHandle)
        CloseHandle(m_ThreadHandle);
    m_ThreadHandle = NULL;
    m_ThreadID = 0;
    return bRet;
}
DWORD WINAPI CThreadClass::ThreadFunc()
{
    for(;;)
    {
        PrintfDescrip();
        Sleep(3000);
    }
    return 0;
}
void main()
{
    CThreadClass t1, t2;
    t1.SetDescrip(“the t1 Member Function Thread run!“);
    t1.RunThread();
    t2.SetDescrip(“the t2 Member Function Thread run!“);
    t2.RunThread();
    getch();
    printf(“wait for TerminateThread...\n“);
    t1.FinishThread();
    t2.FinishThread();
    printf(“exit!\n“);
    getch();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: