好用的win32线程封装类

废话不说,先上代码,此代码源于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;
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值