📄 thread.cpp
字号:
#include <Thread.h>#include <MTL/MTL.h>#include <stdio.h>//stop()之后,必须调用join()释放线程资源//pass an object of Thread_T as arg#ifdef __UNIX__void* thread_routine(void* arg){ int status,cancel_type; //puts("in thread\n"); pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &status); pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &cancel_type); ((Thread_T*)arg)->run(); ((Thread_T*)arg)->setDead(); return NULL;}#endif#ifdef _WIN32DWORD WINAPI thread_routine(LPVOID arg){ ((Thread_T*)arg)->run(); ((Thread_T*)arg)->setDead(); return NULL;}#endif //don't process any exception now#ifdef _WIN32DWORD#endif#ifdef __UNIX__pthread_t #endifThread_T::getID() const{ return threadID;}void Thread_T::start(){#ifdef __UNIX__ int status; status = pthread_create(&threadID, NULL, thread_routine, (void*)this); if ( status != 0) throw MTLSystemCallException("error in call pthread_create", 1000);#endif#ifdef _WIN32 m_threadHandle = CreateThread(NULL, 0, //default stack size thread_routine, (LPVOID)this, 0, //start immediately &threadID); if (m_threadHandle == NULL) throw MTLSystemCallException("error in call pthread_create", 1000);#endif live = true; return;}void Thread_T::join(){#ifdef __UNIX__ int status; status = pthread_join(threadID, NULL); live = false; hasJoined = true; if ( status != 0) throw MTLSystemCallException("error in call pthread_join", 1001);#endif#ifdef _WIN32 DWORD status; status = WaitForSingleObject(m_threadHandle,INFINITE); hasJoined = true; if (status == WAIT_FAILED ) throw MTLSystemCallException("error in call pthread_join", 1001);#endif return;}void Thread_T::stop(){#ifdef __UNIX__ int status; if (live) { status = pthread_cancel(threadID); pthread_join(threadID, NULL); hasJoined = true; }#endif#ifdef _WIN32 if (live) { TerminateThread(m_threadHandle,-1); WaitForSingleObject(m_threadHandle,INFINITE); hasJoined = true; }#endif live = false; return;}bool Thread_T::isAlive() const{ return live;}void Thread_T::setDead(){ live = false;}Thread_T::~Thread_T(){ if (isAlive() ) { stop(); } if (!hasJoined) { // pthread_join(threadID, NULL); #ifdef __UNIX__ pthread_join(threadID, NULL); #endif #ifdef _WIN32 WaitForSingleObject(m_threadHandle,INFINITE); #endif }}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -