好用的win32线程封装类

时间:2021-07-26 21:56:55

废话不说,先上代码,此代码源于Applied C++书
<pre name="code" class="cpp">#ifndef _win32_thread_h_#define _win32_thread_h_// thread.h//  win32 thread wrapper.#ifndef WIN32#error This version of cThread is only valid on win32 platforms#endif// We want this to be compatible with MFC and non-MFC apps#ifdef _AFXDLL#include <afx.h>#else#include <windows.h>#endif#include <process.h>    // _beginthread(), _endthread()#include <iostream>class cThread{public:  cThread  () : threadid_ (-1) {}  ~cThread () { if (threadid_ != -1) stop();} int threadid () const { return threadid_;}  bool start ()   {    threadid_ = _beginthreadex (0, 0, thread_, this,                                CREATE_SUSPENDED, (unsigned int*) &threadid_);    if (threadid_ != 0)      ResumeThread ((HANDLE)threadid_);    return (threadid_ != 0);  }  // Start the thread running  bool stop  ()   {    TerminateThread ((HANDLE) threadid_, -1);    return true;  }  // Stop the thread. Ungraceful and may result in locking/resource problems.  bool wait (unsigned int seconds = 0)  {    DWORD wait = seconds * 1000;    if (wait == 0) wait = INFINITE;    DWORD status = WaitForSingleObject ((HANDLE) threadid_, wait);    return (status != WAIT_TIMEOUT);  }  // Wait for thread to complete  void sleep (unsigned int msec) { Sleep (msec);}  // Sleep for the specified amount of time.protected:  int threadid_;  static unsigned int __stdcall thread_ (void* obj)  {    // Call the overriden thread function    cThread* t = reinterpret_cast<cThread*>(obj);    t->thread ();    return 0;  }  virtual void thread () {    _endthreadex (0);    CloseHandle ((HANDLE) threadid_);  }  // Thread function, Override this in derived classes.};#endif // _win32_thread_h_


 

使用,从cThread派生,实现其thread()函数, 然后创建类的实例,调用start()成员函数即可


#include "thread.h"
#include <stdio.h>
class CTest : public cThread
{
void thread();

};

void CTest::thread()
{
for(int i=0;i<10;i++)
{
printf("thread\n");
Sleep(1000);
}

}
int main(int argc,char** argv)
{
CTest test;
test.start();

return 0;
}