?? thread.h
字號:
#ifndef _THREAD_H
#define _THREAD_H
#include "windows.h"
/// 線程封裝.
class thread_base
{
private:
HANDLE ht; ///< 線程句柄.
volatile bool p; ///< 暫停標志.
volatile bool x; ///< 退出標志.
unsigned long id ; //thread id
/// 線程函數, 供CreateThread()使用.
/// 該功能調用派生類的entry().
static DWORD WINAPI _entry(LPVOID param)
{
thread_base* p = (thread_base*)param;
p->entry() ;
return 0;
}
/// 死等.
void dead_wait()
{
// thread is not even started
// then return immediately
if( !ht )
return;
WaitForSingleObject(ht, INFINITE);
}
/// 關閉線程句柄.
void close_handle()
{
if( !ht )
return;
CloseHandle(ht);
ht = NULL;
}
protected:
/*! \brief 線程入口, 派生類必須實現!!!
* 在線程執行過程中, 派生類有責任在最經常執行的代碼段中
* 時時檢查thrd_check_pause()以及thrd_check_exit()
* 舉例:
* ...
* \code
* if( thrd_check_exit() )
* return; // exit thread
* thrd_check_pause();
* ...
* \endcode
*/
virtual void entry() =0;
/// 檢查暫停請求
inline void check_pause()
{
while(p)
{
Sleep(1); // prevent from sucking all the system resources
}
}
/// 檢查退出請求.
/// @return true 線程請求退出, false 忽略
inline bool check_exit() const
{
return x;
}
/// 等待一會, 防止資源被獨占
void wait_a_while(){Sleep(1);}
public:
/// 構造函數.
thread_base():ht(NULL), x(false), p(false){}
/// 析構函數.
virtual ~thread_base(){thrd_close();}
/// 判斷線程是否結束.
/// @return true 線程已經結束, false 線程還在運行.
bool thrd_is_over()
{
// the thread is not even created
if( !ht )
return true;
// check the thread handle
return WaitForSingleObject(ht, 0) == WAIT_OBJECT_0;
}
/// @name 線程功能.
//@{
/// 啟動線程.
/// @return true 線程啟動成功, false 線程啟動失敗
virtual bool thrd_start(int nPriority)
{
// thread is still running
if( !thrd_is_over() )
return false;
x = false;
// (SECU,STACK,ENTRY, PARAM,RUNNOW?, TH_ID)
ht = CreateThread(NULL, 0, _entry, this, 0, &id) ;
if (ht == NULL) {
char sss[50] ;
sprintf(sss, "CreateThread failed=%ld", GetLastError()) ;
::MessageBox(NULL, sss, "error", MB_OK) ;
return false;
}
SetThreadPriority(ht, nPriority) ;
return true;
}
/// 暫停線程.
virtual void thrd_pause()
{
p = true;
}
/// 繼續暫停的線程.
virtual void thrd_resume()
{
p = false;
}
/// 關閉線程.(停止線程)
virtual DWORD thrd_close(DWORD timeout=5000)
{
// if thread is paused, then resume it.
// so that it could have chance to check exit flag
if( !ht )
return 888 ;
if( p )
thrd_resume();
x = true;
//dead_wait();
DWORD m_tembool = 9999 ;
m_tembool = WaitForSingleObject(ht, timeout) ;
//close_handle();
CloseHandle(ht);
ht = NULL;
return m_tembool ;
}
virtual DWORD thrd_terminate_close()
{
if( !ht )
return 888 ;
x = true;
//AfxEndThread(0);
CloseHandle(ht);
ht = NULL;
return 0 ;
}
bool thrd_is_paused() const {return p;}
//@}
};
#define ID_SELF(x) TRACE(CString(x)+_T(" thrd id: %08lx\n"), GetCurrentThreadId());
#define THREAD_CHECK_EXIT if( check_exit() ) break;
#define THREAD_CHECK_PAUSE check_pause();
#define THREAD_CHECK THREAD_CHECK_EXIT; THREAD_CHECK_PAUSE;
#define THREAD_BEGIN for(;;) { THREAD_CHECK;
#define THREAD_END }
#endif // _THREAD_H
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -