00001 #include "ThreadedObject.h" 00002 00003 static int threadMain(void *arg) 00004 { 00005 ThreadedObject *throbj = (ThreadedObject *)arg; 00006 while(throbj->isRunning()){ 00007 if (!throbj->oneStep()) break; 00008 } 00009 throbj->notifyFinish(); 00010 } 00011 00012 ThreadedObject::ThreadedObject() : 00013 m_isPausing(false), m_isRunning(false), m_thread(NULL) 00014 { 00015 m_sem = SDL_CreateSemaphore(0); 00016 } 00017 00018 ThreadedObject::~ThreadedObject() 00019 { 00020 SDL_DestroySemaphore(m_sem); 00021 } 00022 00023 void ThreadedObject::pause(){ 00024 m_isPausing = true; 00025 } 00026 00027 void ThreadedObject::resume(){ 00028 m_isPausing = false; 00029 SDL_SemPost(m_sem); 00030 } 00031 00032 bool ThreadedObject::isPausing(){ 00033 return m_isPausing; 00034 } 00035 00036 bool ThreadedObject::isRunning(){ 00037 return m_isRunning; 00038 } 00039 00040 bool ThreadedObject::oneStep(){ 00041 if (m_isPausing){ 00042 SDL_SemWait(m_sem); 00043 } 00044 return true; 00045 } 00046 00047 void ThreadedObject::start() 00048 { 00049 if (m_thread) return; 00050 m_isRunning = true; 00051 m_thread = SDL_CreateThread(threadMain, (void *)this); 00052 } 00053 00054 void ThreadedObject::stop() 00055 { 00056 if (m_isPausing) resume(); 00057 m_isRunning = false; 00058 wait(); 00059 } 00060 00061 void ThreadedObject::wait() 00062 { 00063 SDL_WaitThread(m_thread, NULL); 00064 m_thread = NULL; 00065 } 00066 00067 void ThreadedObject::notifyFinish() 00068 { 00069 m_isRunning = false; 00070 }