00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00026 #ifndef OW32_Thread_h
00027 #define OW32_Thread_h
00028
00029 #include <OW32/OW32Libs.h>
00030 #include <OW32/XHANDLE.h>
00031 #include <cassert>
00032 #include <process.h>
00033
00034
00035 namespace OW32
00036 {
00037
00052 class OW32_LIB_EXPORT CThread
00053 {
00054 private:
00056 XHANDLE m_hThread;
00058 DWORD m_dwThreadId;
00060 bool m_bAutoDelete;
00061
00067 static unsigned int __stdcall RedirectThreadFunc(LPVOID arg)
00068 {
00069 return arg ? ((CThread *)arg)->RunHelper() : -1;
00070 }
00071
00076 unsigned int RunHelper()
00077 {
00078 unsigned int ret = (unsigned int)-1;
00079 if (InitInstance()) {
00080 ret = Run();
00081 ExitInstance();
00082 }
00083 if (m_bAutoDelete)
00084 delete this;
00085 return ret;
00086 }
00087
00089 CThread(const CThread& );
00091 CThread& operator=(const CThread& );
00092
00093 public:
00099 CThread(bool bAutoDelete=false) :
00100 m_bAutoDelete(bAutoDelete),
00101 m_dwThreadId((DWORD)-1)
00102 {
00103 }
00104
00106 virtual ~CThread() {}
00107
00113 virtual unsigned int Run()=0;
00114
00122 virtual BOOL InitInstance() { return TRUE; }
00123
00128 virtual void ExitInstance() {}
00129
00133 bool GetAutoDelete() { return m_bAutoDelete; }
00134
00142 void SetAutoDelete(bool bAutoDelete) { m_bAutoDelete = bAutoDelete; }
00143
00147 BOOL Create()
00148 {
00149 unsigned thrdid;
00150 m_hThread = (HANDLE)_beginthreadex(NULL, 0, RedirectThreadFunc, this, 0, &thrdid);
00151 m_dwThreadId = thrdid;
00152 return TRUE;
00153 }
00154
00160 void Close()
00161 {
00162 m_hThread.Close();
00163 }
00164
00168 DWORD Suspend() { return SuspendThread(m_hThread); }
00169
00173 DWORD Resume() { return ResumeThread(m_hThread); }
00174
00178 int GetPriority() { return GetThreadPriority(m_hThread); }
00179
00184 int SetPriority(int nPriority) { return SetThreadPriority(m_hThread, nPriority); }
00185
00191 BOOL PostMessage(UINT Msg, WPARAM wParam, LPARAM lParam)
00192 { return PostThreadMessage(m_dwThreadId, Msg, wParam, lParam); }
00193
00197 HANDLE GetHandle() { return m_hThread; }
00198
00202 DWORD GetId() { return m_dwThreadId; }
00203
00211 BOOL GetExitCode(LPDWORD lpExitCode) {
00212 assert(!m_bAutoDelete);
00213 return ::GetExitCodeThread(m_hThread, lpExitCode);
00214 }
00215
00219 operator HANDLE() { return m_hThread; }
00220
00224 operator DWORD() { return m_dwThreadId; }
00225 };
00226
00227 }
00228
00229 #endif // OW32_Thread_h