📄 thread.cpp
字号:
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///[Thread - Parent class for classes who want to be executed in new thread]////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// This class is for performing functionality without hanging the calling thread.
/// Usage: implementing run() method and call whenever required.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// Written by Nir Dremer
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include <windows.h>
#include <process.h>
#include "Thread.h"
namespace GenLib
{
Thread::Thread()
{
_ID = 0;
_handle = NULL;
_terminationRequested = false;
}
Thread::~Thread()
{
finish();
}
HANDLE Thread::start(const char *name, const bool suspended)
{
_terminationRequested = false;
if (_handle == NULL)
{
_handle =(HANDLE) _beginthreadex(0, 0, &Thread::execute, this, suspended ? CREATE_SUSPENDED : 0, &_ID);
}
return _handle;
}
void Thread::finish()
{
if (_handle != NULL)
{
::CloseHandle(_handle);
_handle = NULL;
}
}
void Thread::waitForExit()
{
if (_handle == NULL)
return;
MSG msg;
while (::WaitForSingleObject(_handle, 30) != WAIT_OBJECT_0)
{
if (::PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
::TranslateMessage(&msg);
::DispatchMessage(&msg);
}
}
}
void Thread::sleep(const unsigned long timeMS)
{
::Sleep(timeMS);
}
unsigned long Thread::getExitCode() const
{
unsigned long code;
if (_handle != NULL)
::GetExitCodeThread(_handle, &code);
else
code = 0;
return code;
}
int Thread::run()
{
return 0;
}
void Thread::shutDown()
{
}
unsigned __stdcall Thread::execute(void* thread)
{
unsigned retval = ((Thread*) thread)->run();
((Thread*) thread)->shutDown();
return retval;
}
void Thread::exit (unsigned long code)
{
_endthreadex(code);
}
unsigned long Thread::suspend()
{
return (_handle != NULL) ? ::SuspendThread(_handle) : 0;
}
unsigned long Thread::resume()
{
return (_handle != NULL) ? ::ResumeThread(_handle) : 0;
}
int Thread::getPriority() const
{
return (_handle != NULL) ? ::GetThreadPriority(_handle) : THREAD_PRIORITY_ERROR_RETURN;
}
bool Thread::setPriority(int priority)
{
return (_handle != NULL) ? ::SetThreadPriority(_handle, priority) != 0 : false;
}
bool Thread::sleep(unsigned long timeMS, bool alertable)
{
return ::SleepEx(timeMS, alertable) != 0;
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -