好用的win32线程封装类
2015-12-11 20:21
344 查看
废话不说,先上代码,此代码源于Applied C++书
使用,从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;
}
<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;
}
相关文章推荐
- Win Server 2008 R2 安装 Oracle 10g
- 面试题7:重建二叉树(offer)
- 第1条:考虑用静态工厂方法代替构造器(第一章:创建和销毁对象)
- php array_walk()函数
- leetcode Group Anagrams
- Imageloader的简单配置
- window.close关闭窗口,不弹出系统提示,直接关闭
- PB中的Describe,Evaluatate,LookUpDisplay小结
- asp.net 导出excel乱码
- IOS核心动画
- VC10中的C++0x特性:Lambdas,auto,以及 static_assert
- 【】
- 阿姆斯特朗数
- NuGet-步步为营,发送类包。
- 上curl java 模拟http请求
- 牛客网练习知识点笔记——Java基础
- 图片焦点轮播效果
- Ten Tips for Writing CS Papers, Part 2
- 【BZOJ 1036】[ZJOI2008]树的统计Count
- leetcode Spiral Matrix