00001 /* 00002 ######################################################################### 00003 # 00004 # This file is part of trustyRC. 00005 # 00006 # trustyRC, fully modular IRC robot 00007 # Copyright (C) 2006-2008 Nicoleau Fabien 00008 # 00009 # trustyRC is free software: you can redistribute it and/or modify 00010 # it under the terms of the GNU General Public License as published by 00011 # the Free Software Foundation, either version 3 of the License, or 00012 # (at your option) any later version. 00013 # 00014 # trustyRC is distributed in the hope that it will be useful, 00015 # but WITHOUT ANY WARRANTY; without even the implied warranty of 00016 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 00017 # GNU General Public License for more details. 00018 # 00019 # You should have received a copy of the GNU General Public License 00020 # along with trustyRC. If not, see <http://www.gnu.org/licenses/>. 00021 # 00022 ######################################################################### 00023 */ 00024 00029 #include "cppthread.h" 00030 #include <iostream> 00031 using namespace std; 00032 00037 CPPThread::CPPThread() { 00038 this->ti.finished = false; 00039 this->ti.running = false; 00040 this->handle = new pthread_t; 00041 } 00042 00046 CPPThread::~CPPThread() { 00047 this->terminate(); 00048 pthread_join (*this->handle, NULL); 00049 delete this->handle; 00050 } 00051 00060 bool CPPThread::exec(threadProcess myThreadProcess,void*args) { 00061 if ( ! this->isRunning() ) { 00062 this->ti.process = myThreadProcess; 00063 this->ti.args = args; 00064 if (pthread_create (this->handle, NULL,CPPThread::threadStartup,&this->ti) < 0) { 00065 return false; 00066 } 00067 return true; 00068 } 00069 return false; 00070 } 00071 00078 void* CPPThread::threadStartup(void*arg) { 00079 threadInfos* ti = (threadInfos*)arg; 00080 ti->running = true; 00081 pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL); 00082 pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL); 00083 ti->process(ti->args); 00084 ti->running = false; 00085 ti->finished = true; 00086 pthread_exit(0); 00087 } 00088 00093 bool CPPThread::terminate() { 00094 if ( this->isRunning() ) { 00095 if (pthread_cancel (*this->handle) != 0) { 00096 return false; 00097 } 00098 ti.running = false; 00099 return true; 00100 } 00101 return false; 00102 } 00103 00108 bool CPPThread::isRunning() { 00109 return this->ti.running; 00110 } 00111 00118 bool CPPThread::isFinished() { 00119 return this->ti.finished; 00120 } 00121 00125 void* CPPThread::join() { 00126 void* ret; 00127 pthread_join(*this->handle,&ret); 00128 return ret; 00129 } 00130 00137 pthread_t* CPPThread::getHandle() { 00138 return this->handle; 00139 }