/*************************************************************************** * Copyright (C) 04/2006 by Olaf Rempel * * razzor@kopf-tisch.de * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #include "thread.h" #define THREAD_STACKSIZE 65536 #define THREAD_READY 0x01 #define THREAD_RUNNING 0x02 #define THREAD_ENDED 0x03 Thread::Thread() : arg(0), tid(0), state(THREAD_READY) {} Thread::~Thread() { switch (state) { case THREAD_RUNNING: cancel(); case THREAD_ENDED: join(); case THREAD_READY: break; } } int Thread::start(void* arg_) { pthread_attr_t attr; if (state != THREAD_READY) return -1; arg = arg_; state = THREAD_RUNNING; pthread_attr_init(&attr); pthread_attr_setstacksize(&attr, THREAD_STACKSIZE); if (pthread_create(&tid, &attr, (Thread::entry), this) != 0) { state = THREAD_READY; return -1; } return 0; } void Thread::cancel() { pthread_cancel(tid); state = THREAD_ENDED; } bool Thread::isRunning() const { return (state == THREAD_RUNNING); } int Thread::join() { void* retval; pthread_join(tid, &retval); state = THREAD_READY; return (int)retval; } void* Thread::entry(void* myself) { Thread* thread = (Thread*)myself; int retval = thread->execute(thread->arg); thread->state = THREAD_ENDED; return (void*)retval; }