好用的win32线程封装类
来源:互联网 发布:mysql blob字段保存 编辑:程序博客网 时间:2024/05/24 03:38
废话不说,先上代码,此代码源于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
- 好用的win32线程封装类
- Thunk技术封装好的win32项目窗口类
- 一个封装好的线程类
- 一个封装好的线程类
- 用C++封装Win32信号量,同步线程
- win32线程简单封装
- win32下线程封装
- 好用的HttpRequest访问封装类
- 好用的HttpRequest访问封装类
- 好用的自定义Log封装类
- 一个好用的 poi封装类
- 关于win32的C++ 类封装
- 封装好的缓存类
- 封装好的分页类
- 封装好的分页类
- 封装的线程注入类
- 封装线程类的方法
- android SharedPreferences封装类 简单 好用的类
- PB中的Describe,Evaluatate,LookUpDisplay小结
- 循环删除List集合的错误
- 第1条:考虑用静态工厂方法代替构造器(第一章:创建和销毁对象)
- leetcode Group Anagrams
- Win Server 2008 R2 安装 Oracle 10g
- 好用的win32线程封装类
- SQL 改写 max decode 联合应用
- 【Linux驱动】轮询操作select()和poll()
- 20151211 OCP 047 40-60
- php array_walk()函数
- 面试题7:重建二叉树(offer)
- java学习笔记之vector的排序
- 牛客网练习知识点笔记——综合
- 游戏服务器架构