Windows API 封装一个Thread类库

  • 使用Windows API 封装一个Thread类库
  • Thread类被继承后,实现派生类自己的run函数即可

  • 注: _beginthreadex的第三个参数传入的是函数指针,静态函数指针非静态函数指针均可;如果是传入的是类的函数,则该函数应为静态函数。

Thread.h

#ifndef __THREAD__
#define __THREAD__

#include <Windows.h>
#include <tchar.h>
#include <process.h>

class Thread 
{  
protected:

    HANDLE hThread;
    unsigned uiThreadId;

    static unsigned __stdcall _run(void * pThis)
    {
        Thread * pthX = (Thread *)pThis;  
        pthX->run();           
        return 1;  
    }

    virtual void run() = 0;

public:  

    void start(DWORD nTimeOutMs=-1)
    {
        this->hThread = (HANDLE) _beginthreadex(
            NULL,
            0,
            Thread::_run,
            this,
            CREATE_SUSPENDED,
            &uiThreadId
            );

        ResumeThread(hThread);
        if (nTimeOutMs != -1 && nTimeOutMs >= 0)
            WaitForSingleObject(hThread, nTimeOutMs);
    }

    ~Thread()
    {
        CloseHandle(hThread);
    }

};  

#endif

猜你喜欢

转载自blog.csdn.net/VonSdite/article/details/81295082